Repository navigation
fix(ui): translate remaining hardcoded labels #2458
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Open
rrewll
wants to merge
5
commits into
Zoo-Code-Org:main
Choose a base branch
from
rrewll:fix/2425-hardcoded-labels
base: main
Could not load branches
Branch not found: {{ refName }}
Loading
Could not load tags
Nothing to show
Loading
Are you sure you want to change the base?
Some commits from the old base branch may be removed from the timeline,
and old review comments may become outdated.
+3,468
−606
Open
Changes from all commits
Commits
Show all changes
5 commits
Select commit
Hold shift + click to select a range
763283a
fix(ui): translate remaining hardcoded labels (#2425)
rrewll d23d4a6
fix: increase code coverage
rrewll bce1f12
fix: missing test for CodeAccordion
rrewll 8283643
fix: fix coderabbit issues + improve top-level options search in cont…
rrewll 399d0b6
fix: fix CodeAccordion.spec.tsx and About.spec.tsx issues
rrewll File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| 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, | ||
| }, | ||
| ], | ||
| }, | ||
| } | ||
| } |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| 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> </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) | ||
| }) | ||
| } | ||
| }) |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.
Oops, something went wrong.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Oops, something went wrong.
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
Uh oh!
There was an error while loading. Please reload this page.