Skip to content

An open source design system that's fully customizable and agent ready

TypeScript

fix(i18n): catch formatter returns and localize helper text (#7849)

nynexman4464c86dc620c020
diff --git a/.changeset/localize-pasted-text-counts-file-size-limits-and-r40m.md b/.changeset/localize-pasted-text-counts-file-size-limits-and-r40m.md
new file mode 100644
index 0000000000..484bd7cb78
--- /dev/null
+++ b/.changeset/localize-pasted-text-counts-file-size-limits-and-r40m.md
@@ -0,0 +1,6 @@
+---
+'@astryxdesign/core': patch
+---
+
+[fix] Localize pasted-text counts, spoken shortcut names and Ctrl/Esc keycaps; format file-size limits with provider-locale digits and translatable units
+@nynexman4464
diff --git a/internal/eslint-plugin-astryx/no-hardcoded-i18n-string.js b/internal/eslint-plugin-astryx/no-hardcoded-i18n-string.js
index 3df9f81b8b..f0f27c2c06 100644
--- a/internal/eslint-plugin-astryx/no-hardcoded-i18n-string.js
+++ b/internal/eslint-plugin-astryx/no-hardcoded-i18n-string.js
@@ -2,9 +2,9 @@
/**
* @file no-hardcoded-i18n-string.js
- * @description Disallow hardcoded English string literals in user-facing
- * props. Any package that ships translatable UI can enable this rule; scope
- * it with the standard flat-config `files: [...]` pattern.
+ * @description Disallow hardcoded English in user-facing text sinks and
+ * formatter/helper returns. Any package that ships translatable UI can enable
+ * this rule; scope it with the standard flat-config `files: [...]` pattern.
*
* The rule itself is filesystem-agnostic — it does not hardcode any path.
* The caller decides where to run it via `files` / `ignores` in the ESLint
@@ -34,6 +34,14 @@
* literals reached through a ternary or an `||`/`??` fallback and the
* literal chunks of an interpolated template are flagged too;
* identifiers and t(...) results are allowed.
+ * 5. Returns from format* and get*String/Text/Label/Message helpers, including
+ * expression-bodied arrows. Helper names are a heuristic, not data-flow
+ * analysis. Obvious CSS serializer names (color, style, shadow, transform,
+ * gradient, length, angle, RGB/HSL/hex) are excluded; text-sink suffixes
+ * such as formatColorLabel remain checked. Standalone px/s/ms/deg unit
+ * chunks after interpolations are CSS fragments, not English. Nested
+ * callbacks are not the enclosing helper's returns. Concatenations and
+ * TypeScript assertions are walked along with templates and fallbacks.
*
* Ignores:
* - Test files (*.test.*, __tests__/**)
@@ -203,6 +211,7 @@ function reportUserFacingLiteralsIn(expr, name, context, isDefault, opts = {}) {
const allowed = opts.allowed;
// Returns true when a report was actually emitted (i.e. not allowlisted).
const report = (node, value) => {
+ if (opts.requireEnglish && !/[A-Za-z]/.test(value)) return false;
if (allowed?.has(value)) return false;
context.report({
node,
@@ -218,13 +227,39 @@ function reportUserFacingLiteralsIn(expr, name, context, isDefault, opts = {}) {
}
return;
case 'TemplateLiteral':
- for (const quasi of expr.quasis) {
+ for (const [index, quasi] of expr.quasis.entries()) {
const raw = quasi.value?.cooked ?? quasi.value?.raw ?? '';
+ // A unit directly following an interpolation is CSS, not English.
+ // Keep space-separated display units and prose such as "s remaining".
+ if (opts.requireEnglish && index > 0 && /^(?:px|s|ms|deg)\s*$/.test(raw)) {
+ continue;
+ }
if (typeof raw === 'string' && looksUserFacing(raw)) {
// One report per template is enough.
if (report(quasi, raw)) return;
}
}
+ for (const expression of expr.expressions) {
+ reportUserFacingLiteralsIn(expression, name, context, isDefault, opts);
+ }
+ return;
+ case 'BinaryExpression':
+ if (expr.operator === '+') {
+ reportUserFacingLiteralsIn(expr.left, name, context, isDefault, opts);
+ reportUserFacingLiteralsIn(expr.right, name, context, isDefault, opts);
+ }
+ return;
+ case 'TSAsExpression':
+ case 'TSTypeAssertion':
+ case 'TSNonNullExpression':
+ case 'TSSatisfiesExpression':
+ reportUserFacingLiteralsIn(
+ expr.expression,
+ name,
+ context,
+ isDefault,
+ opts,
+ );
return;
case 'ConditionalExpression':
reportUserFacingLiteralsIn(expr.consequent, name, context, isDefault, opts);
@@ -242,6 +277,59 @@ function reportUserFacingLiteralsIn(expr, name, context, isDefault, opts = {}) {
}
}
+function isFormatterName(name) {
+ if (typeof name !== 'string') return false;
+ if (
+ !/^format(?:[A-Z_]|$)|^get(?:[A-Z].*)?(?:String|Text|Label|Message)$/.test(name)
+ ) {
+ return false;
+ }
+ // These names describe CSS output, not interface copy. A text-sink suffix
+ // still wins: formatColorLabel is not a color serializer.
+ return !/(?:CSS|Css|Style|Styles|Color|Shadow|Transform|Gradient|Length|Angle|RGB|Rgb|HSL|Hsl|Hex|Transition|Font|Border|GridTemplate|ClassName|MediaQuery|Selector|Path)(?:String|Value)?$/.test(
+ name,
+ );
+}
+
+function getFunctionName(node) {
+ const parent = node.parent;
+ if (
+ parent?.type === 'VariableDeclarator' &&
+ parent.id.type === 'Identifier'
+ ) {
+ return parent.id.name;
+ }
+ if (
+ (parent?.type === 'Property' || parent?.type === 'MethodDefinition' || parent?.type === 'PropertyDefinition') &&
+ !parent.computed
+ ) {
+ return parent.key.type === 'Identifier'
+ ? parent.key.name
+ : parent.key.value;
+ }
+ if (parent?.type === 'AssignmentExpression' && parent.right === node) {
+ const target = parent.left;
+ if (target.type === 'Identifier') return target.name;
+ if (target.type === 'MemberExpression' && !target.computed) return target.property.name;
+ }
+ if (
+ parent?.type === 'CallExpression' && parent.arguments[0] === node &&
+ parent.callee.type === 'Identifier' &&
+ (parent.callee.name === 'useCallback' || parent.callee.name === 'useMemo')
+ ) {
+ return getFunctionName(parent);
+ }
+ return node.id?.name;
+}
+
+function isFunction(node) {
+ return (
+ node.type === 'FunctionDeclaration' ||
+ node.type === 'FunctionExpression' ||
+ node.type === 'ArrowFunctionExpression'
+ );
+}
+
const rule = {
meta: {
type: 'problem',
@@ -259,6 +347,9 @@ const rule = {
'Hardcoded default {{value}} for prop `{{name}}`. ' +
'Use the alias-and-resolve pattern: `{{name}}: {{name}}FromProps` in the destructure, then ' +
'`const {{name}} = {{name}}FromProps ?? t(\'<namespace>.<component>.<key>\');` inside the body.',
+ hardcodedReturn:
+ 'Hardcoded user-facing string {{value}} returned by `{{name}}()`. ' +
+ 'Use one catalog message via the provider-bound translator instead of constructing English text.',
hardcodedCallArg:
'Hardcoded user-facing string {{value}} passed to `{{name}}()`. ' +
'Route through `t(\'<namespace>.<component>.<key>\')` via `useTranslator()` so it can be localized.',
@@ -289,6 +380,27 @@ const rule = {
const allowedCalleeStrings = new Set(options.allowedCalleeStrings ?? []);
return {
+ ReturnStatement(node) {
+ let owner = node.parent;
+ while (owner && !isFunction(owner)) owner = owner.parent;
+ const name = owner && getFunctionName(owner);
+ if (!isFormatterName(name)) return;
+ reportUserFacingLiteralsIn(node.argument, name, context, false, {
+ messageId: 'hardcodedReturn',
+ requireEnglish: true,
+ });
+ },
+
+ ArrowFunctionExpression(node) {
+ if (node.body.type === 'BlockStatement') return;
+ const name = getFunctionName(node);
+ if (!isFormatterName(name)) return;
+ reportUserFacingLiteralsIn(node.body, name, context, false, {
+ messageId: 'hardcodedReturn',
+ requireEnglish: true,
+ });
+ },
+
// 1. JSX attribute string literals: <X label="Cancel">
JSXAttribute(node) {
if (!node.name || node.name.type === 'JSXNamespacedName') return;
diff --git a/internal/eslint-plugin-astryx/no-hardcoded-i18n-string.test.mjs b/internal/eslint-plugin-astryx/no-hardcoded-i18n-string.test.mjs
index 7b56f11249..82400822fd 100644
--- a/internal/eslint-plugin-astryx/no-hardcoded-i18n-string.test.mjs
+++ b/internal/eslint-plugin-astryx/no-hardcoded-i18n-string.test.mjs
@@ -2,9 +2,8 @@
/**
* @file no-hardcoded-i18n-string.test.mjs
- * @description Tests for the no-hardcoded-i18n-string ESLint rule, focused on
- * the call-argument surface (announce() live-region messages) plus a few
- * anchor cases for the pre-existing JSX-attribute surface.
+ * @description Tests for the no-hardcoded-i18n-string ESLint rule: formatter
+ * returns, announce() live-region messages, and JSX-attribute anchors.
*/
import {RuleTester} from 'eslint';
@@ -61,6 +60,56 @@ ruleTester.run('no-hardcoded-i18n-string', noHardcodedI18nStringRule, {
code: "announce('Copied');",
filename: 'CodeBlock.stories.tsx',
},
+ // --- Formatter/helper returns ---
+ {code: "function formatLabel(count) { return t('items.count', {count}); }"},
+ {code: "const getStatusText = () => t('status.ready');"},
+ {code: 'const formatRangeDisplay = (start, end) => `${start} – ${end}`;'},
+ {
+ code: 'function formatDevMessage(prefix, message) { return `${prefix}: ${message}`; }',
+ },
+ {
+ code: 'function formatShortcut(parts) { return `${parts[0]} + ${parts[1]}`; }',
+ },
+ {code: 'function formatValue(value) { return value; }'},
+ {code: 'const formatCount = count => `${count}`;'},
+ {code: "function getIdentifier() { return 'Internal value'; }"},
+ {
+ code: "function formatLabel() { function callback() { return 'Not its return'; } return label; }",
+ },
+ {code: "const formatLabel = () => { return () => 'Not its return'; };"},
+ {code: 'function formatColor(r, g, b) { return `rgb(${r}, ${g}, ${b})`; }'},
+ {code: 'const formatShadow = value => `0 0 ${value}px black`;'},
+ {code: "function getStyleString() { return 'display: flex; gap: 4px'; }"},
+ ...[
+ 'const formatTransition = ms => `opacity ${ms}ms ease`;',
+ 'const formatFont = size => `${size}px Inter, sans-serif`;',
+ 'const formatBorder = width => `${width}px solid currentColor`;',
+ 'const formatGridTemplate = count => `repeat(${count}, 1fr)`;',
+ 'const formatBoxShadowValue = y => `0 ${y}px 2px black`;',
+ 'const getPathString = width => `M 0 0 L ${width} 0`;',
+ 'const getMediaQueryString = width => `(min-width: ${width}px)`;',
+ 'const formatClassName = name => `${name} Button-root`;',
+ ].map(code => ({code})),
+ // CSS units adjacent to interpolated values are serializers, even when
+ // the helper's name is generic or describes a motion role.
+ {code: 'function format(x, y) { return `${x}px ${y}px`; }'},
+ {
+ code: 'function formatMotionRoleValue(duration, bounce) { return `${duration}s ${bounce}`; }',
+ },
+ ...['px', 's', 'ms', 'deg'].map(unit => ({
+ code: `const format = (a, b) => \`\${a}${unit} \${b}${unit}\`;`,
+ })),
+ {code: 'const formatLength = size => `${size}px`;'},
+ {
+ code: "function formatLabel() { return 'No results'; }",
+ filename: 'Labels.test.ts',
+ },
+ {
+ code: "const getStatusText = () => 'Ready';",
+ filename: 'Labels.stories.tsx',
+ },
+ {code: "function formatLabel() { return 'READY_STATE'; }"},
+ {code: "function formatLabel() { return '/assets/icon.svg'; }"},
// --- Pre-existing surfaces still behave ---
{code: "<button aria-label={t('dialog.close')}>x</button>"},
],
@@ -118,6 +167,84 @@ ruleTester.run('no-hardcoded-i18n-string', noHardcodedI18nStringRule, {
code: "announce(emptyText ?? 'No results found');",
errors: [{messageId: 'hardcodedCallArg'}],
},
+ // --- Formatter/helper returns ---
+ ...[
+ 'const getAriaLabel = useCallback(count => `${count} items`, []);',
+ 'const getStatusText = useMemo(() => `Ready to go`, []);',
+ "class Helpers { getStatusText = () => 'Ready'; }",
+ "helpers.formatLabel = () => 'Ready';",
+ "getStatusText = () => 'Ready';",
+ "function format() { return 'No results'; }",
+ "function getString() { return 'No results'; }",
+ 'function formatLabel(count) { return `${count} chars`; }',
+ "function formatFileSize(bytes) { return bytes + ' B'; }",
+ 'const formatLabel = count => `${count} chars`;',
+ 'const formatLabel = function(count) { return `${count} chars`; };',
+ "function getStatusString() { return 'Ready'; }",
+ "const getStatusText = () => 'Ready';",
+ "function getKeyLabel() { return 'Control'; }",
+ "function getErrorMessage() { return 'Try again'; }",
+ 'const helpers = {formatLabel(count) { return `${count} chars`; }};',
+ "class Helpers { getStatusText() { return 'Ready'; } }",
+ "function formatLabel(count) { return (count + ' chars') as string; }",
+ "function formatLabel(count) { return `${count}${' chars'}`; }",
+ 'function formatLabel(count) { return label ?? `${count} chars`; }',
+ "function formatLabel() { return label || 'No results'; }",
+ "function formatLabel() { return 'No ' + 'results'; }",
+ "function outer() { function formatLabel() { return 'Ready'; } }",
+ ].map(code => ({code, errors: [{messageId: 'hardcodedReturn'}]})),
+ {
+ code: "function formatLabel(count) { return count > 1 ? `${count} lines` : 'One line'; }",
+ errors: [{messageId: 'hardcodedReturn'}, {messageId: 'hardcodedReturn'}],
+ },
+ // Non-CSS copy must not be exempted merely for mentioning a CSS term.
+ {
+ code: "function formatColorLabel() { return 'Choose a color'; }",
+ errors: [{messageId: 'hardcodedReturn'}],
+ },
+ // A space between a number and its unit is display text, not CSS.
+ ...['px', 's', 'ms', 'deg'].map(unit => ({
+ code: `const format = value => \`\${value} ${unit}\`;`,
+ errors: [{messageId: 'hardcodedReturn'}],
+ })),
+ // CSS-fragment exemptions must not hide prose or affect other sinks.
+ ...[
+ 'function formatLabel(seconds, count) { return `${seconds}s ${count} remaining`; }',
+ 'function formatLabel(count) { return `${count} seconds remaining`; }',
+ 'function formatLabel(count, total) { return `${count} in ${total}`; }',
+ "function formatLabel() { return 'px '; }",
+ ].map(code => ({code, errors: [{messageId: 'hardcodedReturn'}]})),
+ {
+ code: 'announce(`${duration}s ${bounce}`);',
+ errors: [{messageId: 'hardcodedCallArg'}],
+ },
+ // The callee allowlist must not exempt formatter returns.
+ {
+ code: "function formatLabel() { return 'Copied'; }",
+ options: [{allowedCalleeStrings: ['Copied']}],
+ errors: [{messageId: 'hardcodedReturn'}],
+ },
+ // Concatenation and assertions also preserve the older text sinks.
+ {
+ code: "announce('Added ' + label);",
+ errors: [{messageId: 'hardcodedCallArg'}],
+ },
+ {
+ code: "<X label={'Hello ' + name} />",
+ errors: [{messageId: 'hardcodedString'}],
+ },
+ {
+ code: "<X label={(name ?? 'No name') as string} />",
+ errors: [{messageId: 'hardcodedString'}],
+ },
+ {
+ code: "function Input({label = 'Hello ' + name}) {}",
+ errors: [{messageId: 'hardcodedDefault'}],
+ },
+ {
+ code: "<X aria-label={`${open ? 'Close' : 'Open'}`} />",
+ errors: [{messageId: 'hardcodedString'}, {messageId: 'hardcodedString'}],
+ },
// --- Pre-existing surfaces still behave ---
{
code: '<button aria-label="Close">x</button>',
diff --git a/packages/core/locales/en.json b/packages/core/locales/en.json
index fe0d6d5437..a0e946101a 100644
--- a/packages/core/locales/en.json
+++ b/packages/core/locales/en.json
@@ -391,6 +391,10 @@
"defaultMessage": "Expand",
"description": "Button label on a chip in the chat composer representing a long pasted text block; clicking reveals full content. \"Expand\" here means reveal more, not grow physically."
},
+ "@astryx.chat.pastedText.label": {
+ "defaultMessage": "{lines, plural, =1 {{chars, plural, other {{chars} chars}}} other {{lines} lines, {chars, plural, other {{chars} chars}}}}",
+ "description": "Count label on a pasted-text chip and its hover preview in the chat composer. {lines} is the number of text lines and {chars} is the character count. The single-line branch omits the line count. Translators may reorder the counts and localize the abbreviated units."
+ },
"@astryx.checkboxList.item.checkbox": {
"defaultMessage": "Checkbox",
"description": "Localized hidden text used internally when a rich visible label names the checkbox through aria-labelledby. It does not become the computed name; callers must provide aria-label when rich content has no text."
@@ -1287,6 +1291,18 @@
"defaultMessage": "1 file selected: {fileName}",
"description": "Live-region announcement when a single file is successfully selected."
},
+ "@astryx.fileInput.fileSize.bytes": {
+ "defaultMessage": "{size, number, ::group-off} B",
+ "description": "File-size limit below 1024 bytes in FileInput validation feedback. {size} is a number of bytes. Localize the unit abbreviation; do not add digit grouping."
+ },
+ "@astryx.fileInput.fileSize.kilobytes": {
+ "defaultMessage": "{size, number, :: .0 group-off} KB",
+ "description": "File-size limit from 1024 bytes up to one megabyte in FileInput validation feedback. {size} is bytes divided by 1024, displayed to one decimal place without digit grouping. Localize the unit abbreviation."
+ },
+ "@astryx.fileInput.fileSize.megabytes": {
+ "defaultMessage": "{size, number, :: .0 group-off} MB",
+ "description": "File-size limit of at least one megabyte in FileInput validation feedback. {size} is bytes divided by 1048576, displayed to one decimal place without digit grouping. Localize the unit abbreviation."
+ },
"@astryx.fileInput.filesSelected": {
"defaultMessage": "{count} files selected",
"description": "Live-region announcement when multiple files are successfully selected."
@@ -1307,6 +1323,70 @@
"defaultMessage": "{label}, {fileNames}",
"description": "Accessible name for a FileInput trigger that has files attached, composing the field label with the selected filenames. Example: `Attachments, report.pdf, notes.txt`."
},
+ "@astryx.kbd.key.alt": {
+ "defaultMessage": "Alt",
+ "description": "Spoken name of the Alt modifier key in a keyboard shortcut's accessible name."
+ },
+ "@astryx.kbd.key.backspace": {
+ "defaultMessage": "Backspace",
+ "description": "Spoken name of the Backspace key in a keyboard shortcut's accessible name."
+ },
+ "@astryx.kbd.key.command": {
+ "defaultMessage": "Command",
+ "description": "Spoken name of the Command modifier key on Apple platforms in a keyboard shortcut's accessible name."
+ },
+ "@astryx.kbd.key.control": {
+ "defaultMessage": "Control",
+ "description": "Spoken name of the Control modifier key in a keyboard shortcut's accessible name. Also resolves the mod key on non-Apple platforms."
+ },
+ "@astryx.kbd.key.controlShort": {
+ "defaultMessage": "Ctrl",
+ "description": "Abbreviated visible label of the Control keycap used for mod on non-Apple platforms. Localize to the keyboard's conventional short label."
+ },
+ "@astryx.kbd.key.down": {
+ "defaultMessage": "Down arrow",
+ "description": "Spoken name of the down arrow key in a keyboard shortcut's accessible name."
+ },
+ "@astryx.kbd.key.enter": {
+ "defaultMessage": "Enter",
+ "description": "Spoken name of the Enter or Return key in a keyboard shortcut's accessible name."
+ },
+ "@astryx.kbd.key.escape": {
+ "defaultMessage": "Escape",
+ "description": "Spoken name of the Escape key in a keyboard shortcut's accessible name. Also used for the esc alias."
+ },
+ "@astryx.kbd.key.escapeShort": {
+ "defaultMessage": "Esc",
+ "description": "Abbreviated visible label of the Escape keycap. Also used for the esc alias."
+ },
+ "@astryx.kbd.key.left": {
+ "defaultMessage": "Left arrow",
+ "description": "Spoken name of the left arrow key in a keyboard shortcut's accessible name."
+ },
+ "@astryx.kbd.key.plus": {
+ "defaultMessage": "Plus",
+ "description": "Spoken name of the literal plus key in a keyboard shortcut's accessible name, distinct from the separator between keys."
+ },
+ "@astryx.kbd.key.right": {
+ "defaultMessage": "Right arrow",
+ "description": "Spoken name of the right arrow key in a keyboard shortcut's accessible name."
+ },
+ "@astryx.kbd.key.shift": {
+ "defaultMessage": "Shift",
+ "description": "Spoken name of the Shift modifier key in a keyboard shortcut's accessible name."
+ },
+ "@astryx.kbd.key.tab": {
+ "defaultMessage": "Tab",
+ "description": "Spoken name of the Tab key in a keyboard shortcut's accessible name."
+ },
+ "@astryx.kbd.key.up": {
+ "defaultMessage": "Up arrow",
+ "description": "Spoken name of the up arrow key in a keyboard shortcut's accessible name."
+ },
+ "@astryx.kbd.shortcut": {
+ "defaultMessage": "{shortcut} + {key}",
+ "description": "Combines spoken key names into one keyboard shortcut's accessible name. {shortcut} is the preceding keys and {key} is the next key's localized spoken name. Applied once for each key after the first; translators may change the separator or order."
+ },
"@astryx.keyboardHint.toNavigate": {
"defaultMessage": "to navigate",
"description": "Trailing text in the keyboard-hint badge, shown after arrow-key icons — reads as `← → to navigate`. Lowercase sentence fragment completing the visual phrase; the badge is aria-hidden, so this is for sighted users only."
diff --git a/packages/core/src/Chat/ChatPastedTextToken.test.tsx b/packages/core/src/Chat/ChatPastedTextToken.test.tsx
new file mode 100644
index 0000000000..448ef36b20
--- /dev/null
+++ b/packages/core/src/Chat/ChatPastedTextToken.test.tsx
@@ -0,0 +1,71 @@
+// Copyright (c) Meta Platforms, Inc. and affiliates.
+
+/**
+ * @file ChatPastedTextToken.test.tsx
+ * @input Uses React Testing Library, ChatPastedTextToken, InternationalizationProvider
+ * @output Verifies catalog-backed pasted-text counts and deterministic English fallback
+ */
+
+import {render, screen} from '@testing-library/react';
+import {describe, expect, it} from 'vitest';
+import {InternationalizationProvider} from '../i18n';
+import en from '../../locales/en.json';
+import {ChatPastedTextToken} from './ChatPastedTextToken';
+
+describe('ChatPastedTextToken', () => {
+ it.each([
+ {text: '', label: '0 chars'},
+ {text: 'a', label: '1 chars'},
+ {text: 'hello', label: '5 chars'},
+ {text: 'a\nb', label: '2 lines, 3 chars'},
+ ])(
+ 'preserves the English count label for $text without a provider',
+ ({text, label}) => {
+ render(<ChatPastedTextToken text={text} />);
+ expect(screen.getByText(label)).toBeInTheDocument();
+ },
+ );
+
+ it('keeps 21 lines distinct from exactly one line in a Slavic locale', () => {
+ render(
+ <InternationalizationProvider
+ locale="ru"
+ messages={{
+ ru: {
+ '@astryx.chat.pastedText.label':
+ en['@astryx.chat.pastedText.label'],
+ },
+ }}>
+ <ChatPastedTextToken text={'a\n'.repeat(20) + 'a'} />
+ </InternationalizationProvider>,
+ );
+ expect(screen.getByText('21 lines, 41 chars')).toBeInTheDocument();
+ });
+
+ it('updates both count branches when the provider changes', () => {
+ const overrides = {
+ fr: {
+ '@astryx.chat.pastedText.label':
+ '{lines, plural, =1 {{chars, plural, one {un caractère} other {{chars} caractères}}} other {{chars, plural, one {un caractère} other {{chars} caractères}} sur {lines} lignes}}',
+ },
+ };
+ const {rerender} = render(
+ <InternationalizationProvider locale="fr" overrides={overrides}>
+ <ChatPastedTextToken text="hello" />
+ </InternationalizationProvider>,
+ );
+ expect(screen.getByText('5 caractères')).toBeInTheDocument();
+ rerender(
+ <InternationalizationProvider locale="fr" overrides={overrides}>
+ <ChatPastedTextToken text={'a\nb'} />
+ </InternationalizationProvider>,
+ );
+ expect(screen.getByText('3 caractères sur 2 lignes')).toBeInTheDocument();
+ rerender(
+ <InternationalizationProvider locale="en" overrides={overrides}>
+ <ChatPastedTextToken text={'a\nb'} />
+ </InternationalizationProvider>,
+ );
+ expect(screen.getByText('2 lines, 3 chars')).toBeInTheDocument();
+ });
+});
diff --git a/packages/core/src/Chat/ChatPastedTextToken.tsx b/packages/core/src/Chat/ChatPastedTextToken.tsx
index 2376dd97a3..2a5f2ecd47 100644
--- a/packages/core/src/Chat/ChatPastedTextToken.tsx
+++ b/packages/core/src/Chat/ChatPastedTextToken.tsx
@@ -4,7 +4,7 @@
/**
* @file ChatPastedTextToken.tsx
- * @input Uses React, StyleX, Badge, HoverCard, Button, CodeBlock
+ * @input Uses React, StyleX, Badge, HoverCard, Button, provider-bound translator
* @output Exports ChatPastedTextToken component
* @position Inline token for pasted text with hover card preview + expand
*
@@ -25,7 +25,7 @@ import {
import {Badge} from '../Badge';
import {Button} from '../Button';
import {HoverCard} from '../HoverCard';
-import {useTranslator} from '../i18n';
+import {useTranslator, type TranslatorFn} from '../i18n';
// =============================================================================
// Types
@@ -75,10 +75,11 @@ const styles = stylex.create({
// Helpers
// =============================================================================
-function formatLabel(text: string): string {
- const lines = text.split('\n').length;
- const chars = text.length;
- return lines > 1 ? `${lines} lines, ${chars} chars` : `${chars} chars`;
+function formatLabel(text: string, t: TranslatorFn): string {
+ return t('@astryx.chat.pastedText.label', {
+ lines: text.split('\n').length,
+ chars: text.length,
+ });
}
// =============================================================================
@@ -90,7 +91,7 @@ export function ChatPastedTextToken({
onExpand,
}: ChatPastedTextTokenProps) {
const t = useTranslator();
- const label = formatLabel(text);
+ const label = formatLabel(text, t);
const cardContent = (
<div {...stylex.props(styles.preview)}>
diff --git a/packages/core/src/FileInput/FileInput.test.tsx b/packages/core/src/FileInput/FileInput.test.tsx
index f817ef3fc3..de82a66326 100644
--- a/packages/core/src/FileInput/FileInput.test.tsx
+++ b/packages/core/src/FileInput/FileInput.test.tsx
@@ -511,6 +511,84 @@ describe('FileInput', () => {
});
describe('validation', () => {
+ it.each([
+ {maxSize: 0, expected: '0 B'},
+ {maxSize: 1023, expected: '1023 B'},
+ {maxSize: 1024, expected: '1.0 KB'},
+ {maxSize: 1048575, expected: '1024.0 KB'},
+ {maxSize: 1048576, expected: '1.0 MB'},
+ {maxSize: 1572864, expected: '1.5 MB'},
+ ])(
+ 'preserves the English size boundary at $maxSize bytes',
+ ({maxSize, expected}) => {
+ render(
+ <FileInput
+ label="Upload"
+ value={null}
+ onChange={() => {}}
+ maxSize={maxSize}
+ />,
+ );
+ fireEvent.change(fileInputEl(), {
+ target: {files: [createFile('big.txt', maxSize + 1)]},
+ });
+ expect(
+ screen.getByText(`"big.txt" exceeds ${expected} limit`),
+ ).toBeInTheDocument();
+ },
+ );
+
+ it.each([
+ {
+ maxSize: 512,
+ sizeKey: 'bytes',
+ message: '{size, number} octets',
+ expected: '512 octets',
+ },
+ {
+ maxSize: 1536,
+ sizeKey: 'kilobytes',
+ message: '{size, number, ::.0} ko',
+ expected: '1,5 ko',
+ },
+ {
+ maxSize: 1572864,
+ sizeKey: 'megabytes',
+ message: '{size, number, ::.0} Mo',
+ expected: '1,5 Mo',
+ },
+ ])(
+ 'localizes the $sizeKey size in validation feedback',
+ ({maxSize, sizeKey, message, expected}) => {
+ const handleChange = vi.fn();
+ render(
+ <InternationalizationProvider
+ locale="fr"
+ overrides={{
+ fr: {
+ '@astryx.fileInput.errorMaxSize':
+ '{maxSize} maximum pour {fileName}',
+ [`@astryx.fileInput.fileSize.${sizeKey}`]: message,
+ },
+ }}>
+ <FileInput
+ label="Upload"
+ value={null}
+ onChange={handleChange}
+ maxSize={maxSize}
+ />
+ </InternationalizationProvider>,
+ );
+ fireEvent.change(fileInputEl(), {
+ target: {files: [createFile('big.txt', maxSize + 1)]},
+ });
+ expect(
+ screen.getByText(`${expected} maximum pour big.txt`),
+ ).toBeInTheDocument();
+ expect(handleChange).toHaveBeenCalledWith(null);
+ },
+ );
+
it('rejects files exceeding maxSize', () => {
const handleChange = vi.fn();
render(
diff --git a/packages/core/src/FileInput/FileInput.tsx b/packages/core/src/FileInput/FileInput.tsx
index 574393f331..1ece331f28 100644
--- a/packages/core/src/FileInput/FileInput.tsx
+++ b/packages/core/src/FileInput/FileInput.tsx
@@ -4,7 +4,7 @@
/**
* @file FileInput.tsx
- * @input Uses React, useId, Field, Icon, Spinner, VisuallyHidden
+ * @input Uses React, useId, Field, Icon, Spinner, VisuallyHidden, provider-bound translator
* @output Exports FileInput component, public types, and its root/icon theme targets
* @position Core implementation; consumed by index.ts, tested by FileInput.test.tsx
*
@@ -68,14 +68,16 @@ import {useTranslator} from '../i18n';
import type {TranslatorFn} from '../i18n';
import {useMergedRefs} from '../hooks/useMergedRefs';
-function formatFileSize(bytes: number): string {
+function formatFileSize(bytes: number, t: TranslatorFn): string {
if (bytes < 1024) {
- return `${bytes} B`;
+ return t('@astryx.fileInput.fileSize.bytes', {size: bytes});
}
if (bytes < 1024 * 1024) {
- return `${(bytes / 1024).toFixed(1)} KB`;
+ return t('@astryx.fileInput.fileSize.kilobytes', {size: bytes / 1024});
}
- return `${(bytes / (1024 * 1024)).toFixed(1)} MB`;
+ return t('@astryx.fileInput.fileSize.megabytes', {
+ size: bytes / (1024 * 1024),
+ });
}
function validateFiles(
@@ -116,7 +118,7 @@ function validateFiles(
errors.push(
t('@astryx.fileInput.errorMaxSize', {
fileName: file.name,
- maxSize: formatFileSize(maxSize),
+ maxSize: formatFileSize(maxSize, t),
}),
);
return false;
diff --git a/packages/core/src/Kbd/Kbd.test.tsx b/packages/core/src/Kbd/Kbd.test.tsx
index 9240a6e6b5..0120b9ff0c 100644
--- a/packages/core/src/Kbd/Kbd.test.tsx
+++ b/packages/core/src/Kbd/Kbd.test.tsx
@@ -12,6 +12,7 @@
import {render, screen} from '@testing-library/react';
import {describe, it, expect, afterEach, vi} from 'vitest';
import {Kbd} from './Kbd';
+import {InternationalizationProvider} from '../i18n';
describe('Kbd', () => {
const originalPlatform = navigator.platform;
@@ -186,6 +187,100 @@ describe('Kbd', () => {
expect(el).toHaveAttribute('aria-label', 'Control + K');
});
+ it.each([
+ {platform: 'Linux', key: 'control', expectedGlyph: 'Ctrl'},
+ {platform: 'MacIntel', key: 'command', expectedGlyph: '⌘'},
+ ])(
+ 'localizes modifier labels on $platform without changing the glyph',
+ ({platform, key, expectedGlyph}) => {
+ Object.defineProperty(navigator, 'platform', {
+ value: platform,
+ configurable: true,
+ });
+ const overrides = {
+ fr: {
+ [`@astryx.kbd.key.${key}`]: 'Modificateur',
+ '@astryx.kbd.key.shift': 'Majuscule',
+ },
+ };
+ const {rerender} = render(
+ <InternationalizationProvider locale="fr" overrides={overrides}>
+ <Kbd keys="mod+shift+k" />
+ </InternationalizationProvider>,
+ );
+ expect(screen.getByRole('img')).toHaveAccessibleName(
+ 'Modificateur + Majuscule + K',
+ );
+ expect(screen.getByText(expectedGlyph)).toBeInTheDocument();
+ expect(screen.getByText('⇧')).toBeInTheDocument();
+ rerender(
+ <InternationalizationProvider locale="en" overrides={overrides}>
+ <Kbd keys="mod+shift+k" />
+ </InternationalizationProvider>,
+ );
+ expect(screen.getByRole('img')).toHaveAccessibleName(
+ `${key === 'command' ? 'Command' : 'Control'} + Shift + K`,
+ );
+ },
+ );
+
+ it.each([
+ 'ctrl',
+ 'alt',
+ 'shift',
+ 'enter',
+ 'backspace',
+ 'escape',
+ 'tab',
+ 'up',
+ 'down',
+ 'left',
+ 'right',
+ 'plus',
+ 'esc',
+ 'return',
+ ])('uses a catalog entry for the %s spoken key', key => {
+ const canonical =
+ key === 'ctrl'
+ ? 'control'
+ : key === 'esc'
+ ? 'escape'
+ : key === 'return'
+ ? 'enter'
+ : key;
+ render(
+ <InternationalizationProvider
+ locale="fr"
+ overrides={{fr: {[`@astryx.kbd.key.${canonical}`]: 'Touche traduite'}}}>
+ <Kbd keys={key} />
+ </InternationalizationProvider>,
+ );
+ expect(screen.getByRole('img')).toHaveAccessibleName('Touche traduite');
+ });
+
+ it('localizes visible key text and the spoken shortcut combination', () => {
+ render(
+ <InternationalizationProvider
+ locale="de"
+ overrides={{
+ de: {
+ '@astryx.kbd.key.controlShort': 'Strg',
+ '@astryx.kbd.key.escapeShort': 'Abbr',
+ '@astryx.kbd.key.control': 'Steuerung',
+ '@astryx.kbd.key.escape': 'Abbrechen',
+ '@astryx.kbd.shortcut': '{key} mit {shortcut}',
+ },
+ }}>
+ <Kbd keys="mod+esc" />
+ </InternationalizationProvider>,
+ );
+ expect(screen.getByText('Strg')).toBeInTheDocument();
+ expect(screen.getByText('Abbr')).toBeInTheDocument();
+ expect(screen.getByRole('img')).toHaveAccessibleName(
+ 'Abbrechen mit Steuerung',
+ );
+ });
+
it('computed role and aria-label win over consumer-passed overrides', () => {
// Contract props the component computes must not be clobbered by
// pass-through attributes: {...rest} is spread before role/aria-label.
diff --git a/packages/core/src/Kbd/Kbd.tsx b/packages/core/src/Kbd/Kbd.tsx
index bc62269ea5..6340505199 100644
--- a/packages/core/src/Kbd/Kbd.tsx
+++ b/packages/core/src/Kbd/Kbd.tsx
@@ -4,8 +4,8 @@
/**
* @file Kbd.tsx
- * @input Uses React, StyleX, theme tokens, shortcut key names and aliases
- * @output Exports Kbd component and KbdProps with canonical shortcut labels
+ * @input Uses React, StyleX, theme tokens, shortcut key names, aliases, provider-bound translator
+ * @output Exports Kbd component and KbdProps with localized shortcut text
* @position Core implementation; renders styled keyboard shortcut indicators
*
* SYNC: When modified, update:
@@ -19,6 +19,7 @@ import {mergeProps} from '../utils';
import {isApplePlatform} from '../utils/isApplePlatform';
import type {BaseProps} from '../BaseProps';
import {themeProps} from '../utils/themeProps';
+import {useTranslator, type TranslatorFn} from '../i18n';
import {
colorVars,
spacingVars,
@@ -67,7 +68,6 @@ const KEY_DISPLAY = new Map<string, string>([
['shift', '\u21E7'], // ⇧
['enter', '\u21B5'], // ↵
['backspace', '\u232B'], // ⌫
- ['escape', 'Esc'],
['tab', '\u21E5'], // ⇥
['up', '\u2191'],
['down', '\u2193'],
@@ -86,10 +86,11 @@ const KBD_KEY_ALIASES = new Map<string, string>([
* `mod` key (⌘ on macOS, Ctrl on other platforms) and falls back to
* KEY_DISPLAY or uppercased key name.
*/
-function getKeyDisplay(key: string, isMac: boolean): string {
+function getKeyDisplay(key: string, isMac: boolean, t: TranslatorFn): string {
if (key === 'mod') {
- return isMac ? '\u2318' : 'Ctrl';
+ return isMac ? '\u2318' : t('@astryx.kbd.key.controlShort');
}
+ if (key === 'escape') return t('@astryx.kbd.key.escapeShort');
return KEY_DISPLAY.get(key) ?? key.toUpperCase();
}
@@ -99,25 +100,26 @@ function getKeyDisplay(key: string, isMac: boolean): string {
* accessible name for the shortcut is built from these words instead.
*/
const KEY_LABEL = new Map<string, string>([
- ['ctrl', 'Control'],
- ['alt', 'Alt'],
- ['shift', 'Shift'],
- ['enter', 'Enter'],
- ['backspace', 'Backspace'],
- ['escape', 'Escape'],
- ['tab', 'Tab'],
- ['up', 'Up arrow'],
- ['down', 'Down arrow'],
- ['left', 'Left arrow'],
- ['right', 'Right arrow'],
- ['plus', 'Plus'],
+ ['ctrl', '@astryx.kbd.key.control'],
+ ['alt', '@astryx.kbd.key.alt'],
+ ['shift', '@astryx.kbd.key.shift'],
+ ['enter', '@astryx.kbd.key.enter'],
+ ['backspace', '@astryx.kbd.key.backspace'],
+ ['escape', '@astryx.kbd.key.escape'],
+ ['tab', '@astryx.kbd.key.tab'],
+ ['up', '@astryx.kbd.key.up'],
+ ['down', '@astryx.kbd.key.down'],
+ ['left', '@astryx.kbd.key.left'],
+ ['right', '@astryx.kbd.key.right'],
+ ['plus', '@astryx.kbd.key.plus'],
]);
-function getKeyLabel(key: string, isMac: boolean): string {
+function getKeyLabel(key: string, isMac: boolean, t: TranslatorFn): string {
if (key === 'mod') {
- return isMac ? 'Command' : 'Control';
+ return t(isMac ? '@astryx.kbd.key.command' : '@astryx.kbd.key.control');
}
- return KEY_LABEL.get(key) ?? key.toUpperCase();
+ const labelKey = KEY_LABEL.get(key);
+ return labelKey ? t(labelKey) : key.toUpperCase();
}
function subscribeToPlatformChanges(): () => void {
@@ -164,6 +166,7 @@ export interface KbdProps extends BaseProps<HTMLSpanElement> {
* ```
*/
export function Kbd({keys, ref, xstyle, className, style, ...rest}: KbdProps) {
+ const t = useTranslator();
const isMac = useSyncExternalStore(
subscribeToPlatformChanges,
isApplePlatform,
@@ -186,8 +189,12 @@ export function Kbd({keys, ref, xstyle, className, style, ...rest}: KbdProps) {
// Screen-reader name: the joined spoken labels (e.g. "Command + K"), since
// the visual glyphs below are announced meaninglessly by assistive tech.
const accessibleName = parts
- .map(({key}) => getKeyLabel(key, isMac))
- .join(' + ');
+ .map(({key}) => getKeyLabel(key, isMac, t))
+ .reduce(
+ (shortcut, key, index) =>
+ index === 0 ? key : t('@astryx.kbd.shortcut', {shortcut, key}),
+ '',
+ );
return (
<span
@@ -203,7 +210,7 @@ export function Kbd({keys, ref, xstyle, className, style, ...rest}: KbdProps) {
)}>
{parts.map(({key, reactKey}) => (
<kbd key={reactKey} aria-hidden="true" {...stylex.props(styles.kbd)}>
- {getKeyDisplay(key, isMac)}
+ {getKeyDisplay(key, isMac, t)}
</kbd>
))}
</span>