Skip to content

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

TypeScript

fix(i18n): translate announce() live-region strings (#4920)

nynexman446484ceb39328c1
diff --git a/.changeset/i18n-announce-strings.md b/.changeset/i18n-announce-strings.md
new file mode 100644
index 0000000000..aff461a5cf
--- /dev/null
+++ b/.changeset/i18n-announce-strings.md
@@ -0,0 +1,7 @@
+---
+'@astryxdesign/core': patch
+---
+
+[fix] Screen-reader announcements are now localizable. MultiSelector, Selector, Typeahead, FileInput, Tokenizer, and Lightbox spoke several live-region messages in hardcoded English — selection and result counts, file selections, token add/remove, and gallery position — so they stayed English under an `InternationalizationProvider`. They now resolve through the message catalog like the rest of the UI, and the counts use ICU plurals instead of appending an English "s", so locales with other plural rules read correctly.
+
+@nynexman4464
diff --git a/eslint.config.js b/eslint.config.js
index fdeeff8615..8332150ec8 100644
--- a/eslint.config.js
+++ b/eslint.config.js
@@ -220,14 +220,7 @@ export default defineConfig(
}],
// announce() live-region messages are user-facing text; the rule checks
// them as call arguments (callees defaults to ['announce']).
- // TEMPORARY allowlist: these exact strings predate the check and are
- // being replaced with t(...) in the scan #3 i18n sweep PRs
- // (CodeBlock 'Copied'; MultiSelector 'Selection cleared' /
- // 'All selected'). Remove each entry as its fix merges; delete
- // allowedCalleeStrings entirely once the sweep lands.
- '@astryx/no-hardcoded-i18n-string': [isStrictMode ? 'error' : 'warn', {
- allowedCalleeStrings: ['Copied', 'Selection cleared', 'All selected'],
- }],
+ '@astryx/no-hardcoded-i18n-string': isStrictMode ? 'error' : 'warn',
},
},
// The i18n runtime itself defines the message strings the rest of the
diff --git a/internal/eslint-plugin-astryx/no-hardcoded-i18n-string.js b/internal/eslint-plugin-astryx/no-hardcoded-i18n-string.js
index f8721a774e..3df9f81b8b 100644
--- a/internal/eslint-plugin-astryx/no-hardcoded-i18n-string.js
+++ b/internal/eslint-plugin-astryx/no-hardcoded-i18n-string.js
@@ -30,10 +30,10 @@
* tracing — so any local function named `announce` is checked. That is
* a deliberate simplicity tradeoff: false positives require shadowing
* the hook's conventional name, which the codebase does not do.
- * Only plain string literals and template literals WITHOUT expressions
- * are flagged; templates with interpolations, identifiers, and t(...)
- * results are allowed (interpolated announcements are caught by the
- * i18n sweep, not this conservative check).
+ * The argument is walked the same way JSX attribute values are, so
+ * 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.
*
* Ignores:
* - Test files (*.test.*, __tests__/**)
@@ -58,6 +58,8 @@
* {key: 'contains', label: 'contains'}
* function Foo({label = 'Cancel'})
* announce('Copied');
+ * announce(n === 0 ? 'No results' : 'Results found');
+ * announce(`Added ${label}`);
*
* Options:
* callees: string[] — function names whose first argument is a user-facing
@@ -190,40 +192,48 @@ function shouldIgnoreFile(filename) {
* Deliberately does NOT walk into call expressions, member accesses,
* identifiers, JSX expressions, or arbitrary function bodies — those are
* either already handled (t() calls) or too likely to false-positive.
+ *
+ * `opts.messageId` overrides the reported message (the call-argument surface
+ * has its own wording); `opts.allowed` is a Set of exact string values to skip.
*/
-function reportUserFacingLiteralsIn(expr, name, context, isDefault) {
+function reportUserFacingLiteralsIn(expr, name, context, isDefault, opts = {}) {
if (expr == null) return;
+ const messageId =
+ opts.messageId ?? (isDefault ? 'hardcodedDefault' : 'hardcodedString');
+ const allowed = opts.allowed;
+ // Returns true when a report was actually emitted (i.e. not allowlisted).
+ const report = (node, value) => {
+ if (allowed?.has(value)) return false;
+ context.report({
+ node,
+ messageId,
+ data: {value: JSON.stringify(value), name},
+ });
+ return true;
+ };
switch (expr.type) {
case 'Literal':
if (typeof expr.value === 'string' && looksUserFacing(expr.value)) {
- context.report({
- node: expr,
- messageId: isDefault ? 'hardcodedDefault' : 'hardcodedString',
- data: {value: JSON.stringify(expr.value), name},
- });
+ report(expr, expr.value);
}
return;
case 'TemplateLiteral':
for (const quasi of expr.quasis) {
const raw = quasi.value?.cooked ?? quasi.value?.raw ?? '';
if (typeof raw === 'string' && looksUserFacing(raw)) {
- context.report({
- node: quasi,
- messageId: isDefault ? 'hardcodedDefault' : 'hardcodedString',
- data: {value: JSON.stringify(raw), name},
- });
- return; // one report per template is enough
+ // One report per template is enough.
+ if (report(quasi, raw)) return;
}
}
return;
case 'ConditionalExpression':
- reportUserFacingLiteralsIn(expr.consequent, name, context, isDefault);
- reportUserFacingLiteralsIn(expr.alternate, name, context, isDefault);
+ reportUserFacingLiteralsIn(expr.consequent, name, context, isDefault, opts);
+ reportUserFacingLiteralsIn(expr.alternate, name, context, isDefault, opts);
return;
case 'LogicalExpression':
// Only the right side can be a fallback/default string; the left is a
// condition and its string identity doesn't matter for i18n.
- reportUserFacingLiteralsIn(expr.right, name, context, isDefault);
+ reportUserFacingLiteralsIn(expr.right, name, context, isDefault, opts);
return;
// Anything else (CallExpression like t(...), MemberExpression,
// Identifier, ArrowFunctionExpression body, JSXExpression, etc.) — skip.
@@ -369,10 +379,9 @@ const rule = {
// 4. Call argument: `announce('Copied')`
// Matches by callee NAME only (no import/scope tracing) — see the
- // file header for the rationale and limitation. Deliberately
- // conservative about what counts as hardcoded: plain string
- // literals and expression-free template literals. Templates with
- // interpolations, identifiers, and t(...) calls are all allowed.
+ // file header for the rationale and limitation. The argument goes
+ // through the same walk as JSX attribute values, so a ternary or an
+ // interpolated template is caught like a bare literal.
CallExpression(node) {
if (node.callee.type !== 'Identifier') return;
const name = node.callee.name;
@@ -380,23 +389,9 @@ const rule = {
const arg = node.arguments[0];
if (arg == null) return;
- let value = null;
- if (arg.type === 'Literal' && typeof arg.value === 'string') {
- value = arg.value;
- } else if (
- arg.type === 'TemplateLiteral' &&
- arg.expressions.length === 0 &&
- arg.quasis.length === 1
- ) {
- value = arg.quasis[0].value?.cooked ?? arg.quasis[0].value?.raw;
- }
- if (typeof value !== 'string') return;
- if (!looksUserFacing(value)) return;
- if (allowedCalleeStrings.has(value)) return;
- context.report({
- node: arg,
+ reportUserFacingLiteralsIn(arg, name, context, /*isDefault*/ false, {
messageId: 'hardcodedCallArg',
- data: {value: JSON.stringify(value), name},
+ allowed: allowedCalleeStrings,
});
},
};
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 e28f0a92bb..7b56f11249 100644
--- a/internal/eslint-plugin-astryx/no-hardcoded-i18n-string.test.mjs
+++ b/internal/eslint-plugin-astryx/no-hardcoded-i18n-string.test.mjs
@@ -30,9 +30,12 @@ ruleTester.run('no-hardcoded-i18n-string', noHardcodedI18nStringRule, {
{code: "announce(t('codeblock.announce.copied'));"},
// Variables are fine — we can't know their provenance
{code: 'announce(message);'},
- // Template literal WITH expressions is allowed (conservative check; the
- // interpolated-announcement class is handled by the i18n sweep)
- {code: 'announce(`Added ${item.label}`);'},
+ // Interpolation-only template has no literal chunk to translate
+ {code: 'announce(`${count}`);'},
+ // A ternary between two t() results is the pattern we want
+ {
+ code: "announce(cond ? t('a.b.c') : t('a.b.d'));",
+ },
// Empty string (used to clear the live region) is not user-facing
{code: "announce('');"},
// Identifier-shaped single lowercase word is not user-facing
@@ -88,6 +91,33 @@ ruleTester.run('no-hardcoded-i18n-string', noHardcodedI18nStringRule, {
options: [{callees: ['notify']}],
errors: [{messageId: 'hardcodedCallArg'}],
},
+ // Ternary branches are walked, like an aria-label expression container
+ {
+ code: "announce(n === 0 ? 'No results found' : 'Results found');",
+ errors: [
+ {messageId: 'hardcodedCallArg'},
+ {messageId: 'hardcodedCallArg'},
+ ],
+ },
+ // Only the offending branch is reported
+ {
+ code: "announce(n === 0 ? t('a.b.empty') : 'Results found');",
+ errors: [{messageId: 'hardcodedCallArg'}],
+ },
+ // Interpolated template: the literal chunks are still English
+ {
+ code: 'announce(`Added ${item.label}`);',
+ errors: [{messageId: 'hardcodedCallArg'}],
+ },
+ {
+ code: 'announce(`${count} of ${total} selected`);',
+ errors: [{messageId: 'hardcodedCallArg'}],
+ },
+ // Fallback on the right of ?? / ||
+ {
+ code: "announce(emptyText ?? 'No results found');",
+ errors: [{messageId: 'hardcodedCallArg'}],
+ },
// --- 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 e6a8a45487..d52e0d14b3 100644
--- a/packages/core/locales/en.json
+++ b/packages/core/locales/en.json
@@ -1134,5 +1134,53 @@
"@astryx.commandPalette.footer.close": {
"defaultMessage": "Close",
"description": "Keyboard hint in the CommandPalette footer, paired with the Escape key icon. Tells users Escape dismisses the palette."
+ },
+ "@astryx.multiSelector.selectionCleared": {
+ "defaultMessage": "Selection cleared",
+ "description": "Polite screen-reader announcement after the last selected option in a MultiSelector is deselected. Live-region text, never shown on screen; past participle (\"has been cleared\")."
+ },
+ "@astryx.multiSelector.allSelected": {
+ "defaultMessage": "All selected",
+ "description": "Polite screen-reader announcement after every option in a MultiSelector becomes selected. Live-region text, never shown on screen; \"all\" is a determiner (as in \"all the options\")."
+ },
+ "@astryx.multiSelector.selectionCount": {
+ "defaultMessage": "{count, number} of {total, number} selected",
+ "description": "Polite screen-reader announcement of how many MultiSelector options are selected out of the total, spoken after each toggle. Live-region text, never shown on screen; example: `3 of 12 selected`."
+ },
+ "@astryx.multiSelector.emptySearchResults": {
+ "defaultMessage": "No results found",
+ "description": "Polite screen-reader announcement when a MultiSelector search query matches no options. Live-region text, never shown on screen; neutral tone (not error-y)."
+ },
+ "@astryx.multiSelector.resultCount": {
+ "defaultMessage": "{count, number} {count, plural, one {result} other {results}}",
+ "description": "Polite screen-reader announcement of how many MultiSelector options match the search query, spoken as the user types. Live-region text, never shown on screen; example: `1 result`, `12 results`."
+ },
+ "@astryx.selector.emptySearchResults": {
+ "defaultMessage": "No results found",
+ "description": "Polite screen-reader announcement when a Selector search query matches no options. Live-region text, never shown on screen; neutral tone (not error-y)."
+ },
+ "@astryx.selector.resultCount": {
+ "defaultMessage": "{count, number} {count, plural, one {result} other {results}}",
+ "description": "Polite screen-reader announcement of how many Selector options match the search query, spoken as the user types. Live-region text, never shown on screen; example: `1 result`, `12 results`."
+ },
+ "@astryx.typeahead.resultCount": {
+ "defaultMessage": "{count, number} {count, plural, one {result} other {results}}",
+ "description": "Polite screen-reader announcement of how many suggestions a Typeahead search returned. Live-region text, never shown on screen; example: `1 result`, `12 results`."
+ },
+ "@astryx.tokenizer.tokenAdded": {
+ "defaultMessage": "Added {label}",
+ "description": "Polite screen-reader announcement after a token is added to a Tokenizer, either picked from the suggestions or newly created. Live-region text, never shown on screen; `{label}` is the token's visible text."
+ },
+ "@astryx.tokenizer.tokenRemoved": {
+ "defaultMessage": "Removed {label}",
+ "description": "Polite screen-reader announcement after a token is removed from a Tokenizer, by its × button or by Backspace. Live-region text, never shown on screen; `{label}` is the token's visible text."
+ },
+ "@astryx.lightbox.imagePosition": {
+ "defaultMessage": "Image {index, number} of {total, number}",
+ "description": "Polite screen-reader announcement when a Lightbox moves to a media item that has no alt text. Live-region text, never shown on screen; `{index}` is 1-based, example: `Image 3 of 12`."
+ },
+ "@astryx.lightbox.mediaPosition": {
+ "defaultMessage": "{alt}, {index, number} of {total, number}",
+ "description": "Polite screen-reader announcement when a Lightbox moves to a media item that has alt text, composing that alt with the item's position. Live-region text, never shown on screen; example: `Sunset over the bay, 3 of 12`."
}
}
diff --git a/packages/core/src/FileInput/FileInput.test.tsx b/packages/core/src/FileInput/FileInput.test.tsx
index 3e3a91706d..f57a0b8ea9 100644
--- a/packages/core/src/FileInput/FileInput.test.tsx
+++ b/packages/core/src/FileInput/FileInput.test.tsx
@@ -20,6 +20,12 @@ import {
import userEvent from '@testing-library/user-event';
import {FileInput} from './FileInput';
import {__resetLiveRegionsForTest} from '../hooks/useAnnounce';
+import {InternationalizationProvider} from '../i18n';
+
+// The `=1` branch names the file; the `other` branch must not. Both come from
+// this test, so neither can pass against a hardcoded English string.
+const FILE_SELECTED = 'Un fichier choisi : {fileName}';
+const FILES_SELECTED = '{count, number} fichiers choisis';
afterEach(() => {
__resetLiveRegionsForTest();
@@ -324,23 +330,36 @@ describe('FileInput', () => {
describe('announcements', () => {
it('announces a single file selection politely', async () => {
- render(<FileInput label="Upload" value={null} onChange={() => {}} />);
+ render(
+ <InternationalizationProvider
+ locale="fr"
+ overrides={{fr: {'@astryx.fileInput.fileSelected': FILE_SELECTED}}}>
+ <FileInput label="Upload" value={null} onChange={() => {}} />
+ </InternationalizationProvider>,
+ );
fireEvent.change(fileInputEl(), {
target: {files: [createFile('report.pdf', 100)]},
});
await waitFor(() => {
- expect(politeRegion()).toHaveTextContent('1 file selected: report.pdf');
+ // The single-file key, carrying the file name.
+ expect(politeRegion()?.textContent).toBe(
+ 'Un fichier choisi : report.pdf',
+ );
});
});
it('announces a multi-file count politely', async () => {
render(
- <FileInput
- label="Upload"
- value={null}
- onChange={() => {}}
- isMultiple
- />,
+ <InternationalizationProvider
+ locale="fr"
+ overrides={{fr: {'@astryx.fileInput.filesSelected': FILES_SELECTED}}}>
+ <FileInput
+ label="Upload"
+ value={null}
+ onChange={() => {}}
+ isMultiple
+ />
+ </InternationalizationProvider>,
);
const files = [
createFile('a.txt', 100),
@@ -349,7 +368,32 @@ describe('FileInput', () => {
];
fireEvent.change(fileInputEl(), {target: {files}});
await waitFor(() => {
- expect(politeRegion()).toHaveTextContent('3 files selected');
+ // The multi-file key: a count, and no file name.
+ expect(politeRegion()?.textContent).toBe('3 fichiers choisis');
+ });
+ expect(politeRegion()?.textContent).not.toContain('a.txt');
+ });
+
+ it('speaks the selection from a provider catalog', async () => {
+ render(
+ <InternationalizationProvider
+ locale="fr"
+ messages={{
+ fr: {
+ '@astryx.fileInput.fileSelected': {defaultMessage: FILE_SELECTED},
+ },
+ }}>
+ <FileInput label="Upload" value={null} onChange={() => {}} />
+ </InternationalizationProvider>,
+ );
+ fireEvent.change(fileInputEl(), {
+ target: {files: [createFile('report.pdf', 100)]},
+ });
+ await waitFor(() => {
+ // Same key through the catalog path rather than `overrides`.
+ expect(politeRegion()?.textContent).toBe(
+ 'Un fichier choisi : report.pdf',
+ );
});
});
diff --git a/packages/core/src/Lightbox/Lightbox.test.tsx b/packages/core/src/Lightbox/Lightbox.test.tsx
index 396ad34e00..531c69c41b 100644
--- a/packages/core/src/Lightbox/Lightbox.test.tsx
+++ b/packages/core/src/Lightbox/Lightbox.test.tsx
@@ -4,6 +4,7 @@ import {describe, it, expect, vi, beforeEach, afterEach} from 'vitest';
import {render, screen, fireEvent, waitFor} from '@testing-library/react';
import {Lightbox} from './Lightbox';
import {__resetLiveRegionsForTest} from '../hooks/useAnnounce';
+import {InternationalizationProvider} from '../i18n';
// Mock showModal/close for jsdom
beforeEach(() => {
@@ -27,6 +28,17 @@ function politeRegion(): HTMLElement | null {
return document.querySelector('[data-astryx-live-region="polite"]');
}
+// Both position messages, supplied by the test. Overriding the pair means an
+// assertion also proves which of the two keys the component reached for.
+const POSITION_MESSAGES = {
+ fr: {
+ '@astryx.lightbox.mediaPosition':
+ '{alt}, vue {index, number} sur {total, number}',
+ '@astryx.lightbox.imagePosition':
+ 'Photo {index, number} sur {total, number}',
+ },
+};
+
describe('Lightbox', () => {
it('renders as a dialog element', () => {
render(
@@ -320,47 +332,53 @@ describe('Lightbox', () => {
it('announces the new image and position when navigating next via button', async () => {
render(
- <Lightbox
- isOpen={true}
- onOpenChange={() => {}}
- media={media}
- defaultIndex={0}
- />,
+ <InternationalizationProvider locale="fr" overrides={POSITION_MESSAGES}>
+ <Lightbox
+ isOpen={true}
+ onOpenChange={() => {}}
+ media={media}
+ defaultIndex={0}
+ />
+ </InternationalizationProvider>,
);
fireEvent.click(screen.getByLabelText('Next'));
await waitFor(() => {
- expect(politeRegion()).toHaveTextContent('Image B, 2 of 3');
+ expect(politeRegion()?.textContent).toBe('Image B, vue 2 sur 3');
});
});
it('announces the new image and position when navigating via arrow keys', async () => {
render(
- <Lightbox
- isOpen={true}
- onOpenChange={() => {}}
- media={media}
- defaultIndex={1}
- />,
+ <InternationalizationProvider locale="fr" overrides={POSITION_MESSAGES}>
+ <Lightbox
+ isOpen={true}
+ onOpenChange={() => {}}
+ media={media}
+ defaultIndex={1}
+ />
+ </InternationalizationProvider>,
);
const dialog = document.querySelector('dialog')!;
fireEvent.keyDown(dialog, {key: 'ArrowRight'});
await waitFor(() => {
- expect(politeRegion()).toHaveTextContent('Image C, 3 of 3');
+ expect(politeRegion()?.textContent).toBe('Image C, vue 3 sur 3');
});
});
it('announces the new image and position when navigating prev', async () => {
render(
- <Lightbox
- isOpen={true}
- onOpenChange={() => {}}
- media={media}
- defaultIndex={2}
- />,
+ <InternationalizationProvider locale="fr" overrides={POSITION_MESSAGES}>
+ <Lightbox
+ isOpen={true}
+ onOpenChange={() => {}}
+ media={media}
+ defaultIndex={2}
+ />
+ </InternationalizationProvider>,
);
fireEvent.click(screen.getByLabelText('Previous'));
await waitFor(() => {
- expect(politeRegion()).toHaveTextContent('Image B, 2 of 3');
+ expect(politeRegion()?.textContent).toBe('Image B, vue 2 sur 3');
});
});
@@ -370,16 +388,19 @@ describe('Lightbox', () => {
{src: '/b.jpg', alt: ''},
];
render(
- <Lightbox
- isOpen={true}
- onOpenChange={() => {}}
- media={unlabeled}
- defaultIndex={0}
- />,
+ <InternationalizationProvider locale="fr" overrides={POSITION_MESSAGES}>
+ <Lightbox
+ isOpen={true}
+ onOpenChange={() => {}}
+ media={unlabeled}
+ defaultIndex={0}
+ />
+ </InternationalizationProvider>,
);
fireEvent.click(screen.getByLabelText('Next'));
await waitFor(() => {
- expect(politeRegion()).toHaveTextContent('Image 2 of 2');
+ // imagePosition, not a mediaPosition with an empty {alt}.
+ expect(politeRegion()?.textContent).toBe('Photo 2 sur 2');
});
});
diff --git a/packages/core/src/Lightbox/Lightbox.tsx b/packages/core/src/Lightbox/Lightbox.tsx
index 12470b1d66..cd967d0f2e 100644
--- a/packages/core/src/Lightbox/Lightbox.tsx
+++ b/packages/core/src/Lightbox/Lightbox.tsx
@@ -378,9 +378,13 @@ export function Lightbox({
return;
}
const item = mediaArray[Math.min(index, mediaArray.length - 1)];
- const position = `${index + 1} of ${mediaArray.length}`;
- announce(item?.alt ? `${item.alt}, ${position}` : `Image ${position}`);
- }, [index, isOpen, announce, mediaArray]);
+ const position = {index: index + 1, total: mediaArray.length};
+ announce(
+ item?.alt
+ ? t('@astryx.lightbox.mediaPosition', {alt: item.alt, ...position})
+ : t('@astryx.lightbox.imagePosition', position),
+ );
+ }, [index, isOpen, announce, mediaArray, t]);
// Open/close dialog
useIsomorphicLayoutEffect(() => {
diff --git a/packages/core/src/MultiSelector/MultiSelector.test.tsx b/packages/core/src/MultiSelector/MultiSelector.test.tsx
index f4a5547fce..34f20e8a68 100644
--- a/packages/core/src/MultiSelector/MultiSelector.test.tsx
+++ b/packages/core/src/MultiSelector/MultiSelector.test.tsx
@@ -20,6 +20,7 @@ import {
import userEvent from '@testing-library/user-event';
import {MultiSelector} from './MultiSelector';
import {Icon} from '../Icon';
+import {InternationalizationProvider} from '../i18n';
import {__resetLiveRegionsForTest} from '../hooks/useAnnounce';
import {defineTheme} from '../theme/defineTheme';
import {generateThemeCSS} from '../theme/generateThemeRules';
@@ -829,56 +830,112 @@ describe('MultiSelector', () => {
it('announces the match count politely while searching', async () => {
const user = userEvent.setup();
render(
- <MultiSelector
- label="Fruit"
- options={defaultOptions}
- value={EMPTY_VALUE}
- onChange={() => {}}
- hasSearch
- />,
+ <InternationalizationProvider
+ locale="fr"
+ overrides={{
+ fr: {
+ '@astryx.multiSelector.resultCount':
+ '{count, number} {count, plural, one {résultat} other {résultats}}',
+ },
+ }}>
+ <MultiSelector
+ label="Fruit"
+ options={defaultOptions}
+ value={EMPTY_VALUE}
+ onChange={() => {}}
+ hasSearch
+ />
+ </InternationalizationProvider>,
);
await user.click(screen.getByRole('button', {name: 'Fruit'}));
// "an" matches Banana and Orange.
await user.type(screen.getByRole('combobox', h), 'an');
await waitFor(() => {
- expect(politeRegion()).toHaveTextContent('2 results');
+ // The plural branch of a message no catalog supplies.
+ expect(politeRegion()?.textContent).toBe('2 résultats');
});
});
it('announces the singular form when one option matches', async () => {
const user = userEvent.setup();
render(
- <MultiSelector
- label="Fruit"
- options={defaultOptions}
- value={EMPTY_VALUE}
- onChange={() => {}}
- hasSearch
- />,
+ <InternationalizationProvider
+ locale="fr"
+ overrides={{
+ fr: {
+ '@astryx.multiSelector.resultCount':
+ '{count, number} {count, plural, one {résultat} other {résultats}}',
+ },
+ }}>
+ <MultiSelector
+ label="Fruit"
+ options={defaultOptions}
+ value={EMPTY_VALUE}
+ onChange={() => {}}
+ hasSearch
+ />
+ </InternationalizationProvider>,
);
await user.click(screen.getByRole('button', {name: 'Fruit'}));
- // "app" matches only Apple. Anchored so it cannot pass on "1 results".
+ // "app" matches only Apple. Exact match, so "1 résultats" would fail.
await user.type(screen.getByRole('combobox', h), 'app');
await waitFor(() => {
- expect(politeRegion()).toHaveTextContent(/^1 result$/);
+ expect(politeRegion()?.textContent).toBe('1 résultat');
});
});
- it('announces "No results found" when nothing matches', async () => {
+ it('announces the empty-results message when nothing matches', async () => {
const user = userEvent.setup();
render(
- <MultiSelector
- label="Fruit"
- options={defaultOptions}
- value={EMPTY_VALUE}
- onChange={() => {}}
- hasSearch
- />,
+ <InternationalizationProvider
+ locale="fr"
+ overrides={{
+ fr: {'@astryx.multiSelector.emptySearchResults': 'Aucun résultat'},
+ }}>
+ <MultiSelector
+ label="Fruit"
+ options={defaultOptions}
+ value={EMPTY_VALUE}
+ onChange={() => {}}
+ hasSearch
+ />
+ </InternationalizationProvider>,
);
await user.click(screen.getByRole('button', {name: 'Fruit'}));
await user.type(screen.getByRole('combobox', h), 'xyz');
await waitFor(() => {
- expect(politeRegion()).toHaveTextContent('No results found');
+ expect(politeRegion()?.textContent).toBe('Aucun résultat');
+ });
+ });
+
+ it('speaks the result count from a provider catalog (plural)', async () => {
+ const user = userEvent.setup();
+ render(
+ <InternationalizationProvider
+ locale="fr"
+ messages={{
+ fr: {
+ '@astryx.multiSelector.resultCount': {
+ defaultMessage:
+ '{count, number} {count, plural, one {résultat} other {résultats}}',
+ },
+ },
+ }}>
+ <MultiSelector
+ label="Fruit"
+ options={defaultOptions}
+ value={EMPTY_VALUE}
+ onChange={() => {}}
+ hasSearch
+ />
+ </InternationalizationProvider>,
+ );
+ await user.click(screen.getByRole('button', {name: 'Fruit'}));
+ // "an" matches Banana and Orange.
+ await user.type(screen.getByRole('combobox', h), 'an');
+ await waitFor(() => {
+ // Same key through the catalog path rather than `overrides`.
+ expect(politeRegion()?.textContent).toBe('2 résultats');
});
});
@@ -1190,53 +1247,109 @@ describe('MultiSelector', () => {
it('announces the selection count politely when toggling an option', async () => {
const user = userEvent.setup();
render(
- <MultiSelector
- label="Fruit"
- options={[...ANNOUNCE_OPTIONS]}
- value={EMPTY_VALUE}
- onChange={() => {}}
- />,
+ <InternationalizationProvider
+ locale="fr"
+ overrides={{
+ fr: {
+ '@astryx.multiSelector.selectionCount':
+ '{count, number} sur {total, number} sélectionnés',
+ },
+ }}>
+ <MultiSelector
+ label="Fruit"
+ options={[...ANNOUNCE_OPTIONS]}
+ value={EMPTY_VALUE}
+ onChange={() => {}}
+ />
+ </InternationalizationProvider>,
);
await user.click(screen.getByRole('combobox'));
const options = screen.getAllByRole('option', {hidden: true});
await user.click(options[0]);
await waitFor(() => {
- expect(politeRegion()).toHaveTextContent('1 of 3 selected');
+ // Both arguments land, in the order the message asks for them.
+ expect(politeRegion()?.textContent).toBe('1 sur 3 sélectionnés');
});
});
- it('announces "All selected" when select-all selects everything', async () => {
+ it('announces the all-selected message when select-all selects everything', async () => {
const user = userEvent.setup();
render(
- <MultiSelector
- label="Fruit"
- options={[...ANNOUNCE_OPTIONS]}
- value={EMPTY_VALUE}
- onChange={() => {}}
- hasSelectAll
- />,
+ <InternationalizationProvider
+ locale="fr"
+ overrides={{
+ fr: {'@astryx.multiSelector.allSelected': 'Tout est là'},
+ }}>
+ <MultiSelector
+ label="Fruit"
+ options={[...ANNOUNCE_OPTIONS]}
+ value={EMPTY_VALUE}
+ onChange={() => {}}
+ hasSelectAll
+ />
+ </InternationalizationProvider>,
);
await user.click(screen.getByRole('combobox'));
await user.click(screen.getByText('Select all'));
await waitFor(() => {
- expect(politeRegion()).toHaveTextContent('All selected');
+ expect(politeRegion()?.textContent).toBe('Tout est là');
});
});
- it('announces "Selection cleared" when clearing', async () => {
+ it('announces the selection-cleared message when clearing', async () => {
const user = userEvent.setup();
render(
- <MultiSelector
- label="Fruit"
- options={[...ANNOUNCE_OPTIONS]}
- value={['Apple', 'Banana']}
- onChange={() => {}}
- hasClear
- />,
+ <InternationalizationProvider
+ locale="fr"
+ overrides={{
+ fr: {'@astryx.multiSelector.selectionCleared': 'Plus rien'},
+ }}>
+ <MultiSelector
+ label="Fruit"
+ options={[...ANNOUNCE_OPTIONS]}
+ value={['Apple', 'Banana']}
+ onChange={() => {}}
+ hasClear
+ />
+ </InternationalizationProvider>,
);
await user.click(screen.getByRole('button', {name: 'Clear all Fruit'}));
await waitFor(() => {
- expect(politeRegion()).toHaveTextContent('Selection cleared');
+ expect(politeRegion()?.textContent).toBe('Plus rien');
+ });
+ });
+
+ it('prefers a provider override over the provider catalog', async () => {
+ const user = userEvent.setup();
+ render(
+ <InternationalizationProvider
+ locale="fr"
+ messages={{
+ fr: {
+ '@astryx.multiSelector.selectionCount': {
+ defaultMessage: '{count, number} du catalogue',
+ },
+ },
+ }}
+ overrides={{
+ fr: {
+ '@astryx.multiSelector.selectionCount':
+ '{count, number} remplacé',
+ },
+ }}>
+ <MultiSelector
+ label="Fruit"
+ options={[...ANNOUNCE_OPTIONS]}
+ value={EMPTY_VALUE}
+ onChange={() => {}}
+ />
+ </InternationalizationProvider>,
+ );
+ await user.click(screen.getByRole('combobox'));
+ const options = screen.getAllByRole('option', {hidden: true});
+ await user.click(options[0]);
+ await waitFor(() => {
+ expect(politeRegion()?.textContent).toBe('1 remplacé');
});
});
});
diff --git a/packages/core/src/MultiSelector/MultiSelector.tsx b/packages/core/src/MultiSelector/MultiSelector.tsx
index 10b16b1589..08cad69334 100644
--- a/packages/core/src/MultiSelector/MultiSelector.tsx
+++ b/packages/core/src/MultiSelector/MultiSelector.tsx
@@ -792,14 +792,19 @@ export function MultiSelector<T extends MultiSelectorOptionType>({
const selectableSet = new Set(selectableItems.map(item => item.value));
const selectedCount = nextValue.filter(v => selectableSet.has(v)).length;
if (selectedCount === 0) {
- announce('Selection cleared');
+ announce(t('@astryx.multiSelector.selectionCleared'));
} else if (total > 0 && selectedCount === total) {
- announce('All selected');
+ announce(t('@astryx.multiSelector.allSelected'));
} else {
- announce(`${selectedCount} of ${total} selected`);
+ announce(
+ t('@astryx.multiSelector.selectionCount', {
+ count: selectedCount,
+ total,
+ }),
+ );
}
},
- [announce, selectableItems],
+ [announce, selectableItems, t],
);
// Filter items by search query
@@ -903,11 +908,11 @@ export function MultiSelector<T extends MultiSelectorOptionType>({
const count = filterOptionsByQuery(selectableItems, nextQuery).length;
announce(
count === 0
- ? 'No results found'
- : `${count} result${count === 1 ? '' : 's'}`,
+ ? t('@astryx.multiSelector.emptySearchResults')
+ : t('@astryx.multiSelector.resultCount', {count}),
);
},
- [announce, selectableItems],
+ [announce, selectableItems, t],
);
// Handle toggle
diff --git a/packages/core/src/Selector/Selector.test.tsx b/packages/core/src/Selector/Selector.test.tsx
index 7901830477..301b75f60a 100644
--- a/packages/core/src/Selector/Selector.test.tsx
+++ b/packages/core/src/Selector/Selector.test.tsx
@@ -26,6 +26,7 @@ import {RadioIndicator} from '../Indicator';
import {InputGroup, InputGroupText} from '../InputGroup';
import {__resetLiveRegionsForTest} from '../hooks/useAnnounce';
import {__resetInteractionModalityForTest} from '../utils/interactionModality';
+import {InternationalizationProvider} from '../i18n';
import {defineTheme} from '../theme/defineTheme';
import {Theme} from '../theme/Theme';
import {generateThemeCSS} from '../theme/generateThemeRules';
@@ -1037,56 +1038,81 @@ describe('Selector', () => {
it('announces the match count politely while searching', async () => {
const user = userEvent.setup();
render(
- <Selector
- label="Fruit"
- options={OPTIONS}
- value="Apple"
- onChange={() => {}}
- hasSearch
- />,
+ <InternationalizationProvider
+ locale="fr"
+ overrides={{
+ fr: {
+ '@astryx.selector.resultCount':
+ '{count, number} {count, plural, one {résultat} other {résultats}}',
+ },
+ }}>
+ <Selector
+ label="Fruit"
+ options={OPTIONS}
+ value="Apple"
+ onChange={() => {}}
+ hasSearch
+ />
+ </InternationalizationProvider>,
);
await user.click(screen.getByRole('button', {name: 'Fruit'}));
// "a" matches Apple and Banana.
await user.type(screen.getByRole('combobox', h), 'a');
await waitFor(() => {
- expect(politeRegion()).toHaveTextContent('2 results');
+ // The plural branch of a message no catalog supplies.
+ expect(politeRegion()?.textContent).toBe('2 résultats');
});
});
it('announces the singular form when one option matches', async () => {
const user = userEvent.setup();
render(
- <Selector
- label="Fruit"
- options={OPTIONS}
- value="Apple"
- onChange={() => {}}
- hasSearch
- />,
+ <InternationalizationProvider
+ locale="fr"
+ overrides={{
+ fr: {
+ '@astryx.selector.resultCount':
+ '{count, number} {count, plural, one {résultat} other {résultats}}',
+ },
+ }}>
+ <Selector
+ label="Fruit"
+ options={OPTIONS}
+ value="Apple"
+ onChange={() => {}}
+ hasSearch
+ />
+ </InternationalizationProvider>,
);
await user.click(screen.getByRole('button', {name: 'Fruit'}));
- // "ban" matches only Banana. Anchored so it cannot pass on "1 results".
+ // "ban" matches only Banana. Exact, so "1 résultats" would fail.
await user.type(screen.getByRole('combobox', h), 'ban');
await waitFor(() => {
- expect(politeRegion()).toHaveTextContent(/^1 result$/);
+ expect(politeRegion()?.textContent).toBe('1 résultat');
});
});
- it('announces "No results found" when nothing matches', async () => {
+ it('announces the empty-results message when nothing matches', async () => {
const user = userEvent.setup();
render(
- <Selector
- label="Fruit"
- options={OPTIONS}
- value="Apple"
- onChange={() => {}}
- hasSearch
- />,
+ <InternationalizationProvider
+ locale="fr"
+ overrides={{
+ fr: {'@astryx.selector.emptySearchResults': 'Aucun résultat'},
+ }}>
+ <Selector
+ label="Fruit"
+ options={OPTIONS}
+ value="Apple"
+ onChange={() => {}}
+ hasSearch
+ />
+ </InternationalizationProvider>,
);
await user.click(screen.getByRole('button', {name: 'Fruit'}));
await user.type(screen.getByRole('combobox', h), 'xyz');
await waitFor(() => {
- expect(politeRegion()).toHaveTextContent('No results found');
+ expect(politeRegion()?.textContent).toBe('Aucun résultat');
});
});
diff --git a/packages/core/src/Selector/Selector.tsx b/packages/core/src/Selector/Selector.tsx
index b6c0fc7458..41e5387fe9 100644
--- a/packages/core/src/Selector/Selector.tsx
+++ b/packages/core/src/Selector/Selector.tsx
@@ -844,11 +844,11 @@ export function Selector<T extends SelectorOptionType>(
const count = filterOptionsByQuery(selectableItems, nextQuery).length;
announce(
count === 0
- ? 'No results found'
- : `${count} result${count === 1 ? '' : 's'}`,
+ ? t('@astryx.selector.emptySearchResults')
+ : t('@astryx.selector.resultCount', {count}),
);
},
- [announce, selectableItems],
+ [announce, selectableItems, t],
);
// Calculate offset to position selected item over trigger. Explicit
diff --git a/packages/core/src/Tokenizer/Tokenizer.test.tsx b/packages/core/src/Tokenizer/Tokenizer.test.tsx
index af82af4f9f..51c70d2765 100644
--- a/packages/core/src/Tokenizer/Tokenizer.test.tsx
+++ b/packages/core/src/Tokenizer/Tokenizer.test.tsx
@@ -16,6 +16,16 @@ import {Tokenizer} from './Tokenizer';
import {__resetLiveRegionsForTest} from '../hooks/useAnnounce';
import type {SearchSource, SearchableItem} from '../Typeahead/types';
import {TestIcon} from '../__tests__/TestIcon';
+import {InternationalizationProvider} from '../i18n';
+
+// Test-supplied announcement strings: the assertions below depend on no
+// catalog, and no hardcoded English in the component can satisfy them.
+const TOKEN_MESSAGES = {
+ fr: {
+ '@astryx.tokenizer.tokenAdded': 'Ajouté : {label}',
+ '@astryx.tokenizer.tokenRemoved': 'Retiré : {label}',
+ },
+};
function politeRegion(): HTMLElement | null {
return document.querySelector('[data-astryx-live-region="polite"]');
@@ -980,12 +990,14 @@ describe('Tokenizer', () => {
it('announces removal politely on Backspace with an empty input', async () => {
const onChange = vi.fn();
render(
- <Tokenizer
- label="Members"
- searchSource={userSource}
- value={[users[0], users[1]]}
- onChange={onChange}
- />,
+ <InternationalizationProvider locale="fr" overrides={TOKEN_MESSAGES}>
+ <Tokenizer
+ label="Members"
+ searchSource={userSource}
+ value={[users[0], users[1]]}
+ onChange={onChange}
+ />
+ </InternationalizationProvider>,
);
const input = screen.getByRole('combobox');
fireEvent.keyDown(input, {key: 'Backspace'});
@@ -994,35 +1006,39 @@ describe('Tokenizer', () => {
type: 'remove',
});
await waitFor(() => {
- expect(politeRegion()).toHaveTextContent('Removed Bob');
+ expect(politeRegion()?.textContent).toBe('Retiré : Bob');
});
});
it("announces removal politely when clicking a token's remove button", async () => {
render(
- <Tokenizer
- label="Members"
- searchSource={userSource}
- value={[users[0], users[1]]}
- onChange={() => {}}
- />,
+ <InternationalizationProvider locale="fr" overrides={TOKEN_MESSAGES}>
+ <Tokenizer
+ label="Members"
+ searchSource={userSource}
+ value={[users[0], users[1]]}
+ onChange={() => {}}
+ />
+ </InternationalizationProvider>,
);
fireEvent.click(screen.getByRole('button', {name: 'Remove Alice'}));
await waitFor(() => {
- expect(politeRegion()).toHaveTextContent('Removed Alice');
+ expect(politeRegion()?.textContent).toBe('Retiré : Alice');
});
});
it('announces addition politely when selecting a search result', async () => {
render(
- <Tokenizer
- label="Members"
- searchSource={userSource}
- value={[]}
- onChange={() => {}}
- hasEntriesOnFocus
- debounceMs={0}
- />,
+ <InternationalizationProvider locale="fr" overrides={TOKEN_MESSAGES}>
+ <Tokenizer
+ label="Members"
+ searchSource={userSource}
+ value={[]}
+ onChange={() => {}}
+ hasEntriesOnFocus
+ debounceMs={0}
+ />
+ </InternationalizationProvider>,
);
const input = screen.getByRole('combobox');
fireEvent.focus(input);
@@ -1031,7 +1047,7 @@ describe('Tokenizer', () => {
});
fireEvent.click(screen.getByText('Alice'));
await waitFor(() => {
- expect(politeRegion()).toHaveTextContent('Added Alice');
+ expect(politeRegion()?.textContent).toBe('Ajouté : Alice');
});
});
@@ -1041,14 +1057,16 @@ describe('Tokenizer', () => {
bootstrap: () => [],
};
render(
- <Tokenizer
- label="Tags"
- searchSource={emptySource}
- value={[]}
- onChange={() => {}}
- hasCreate
- debounceMs={0}
- />,
+ <InternationalizationProvider locale="fr" overrides={TOKEN_MESSAGES}>
+ <Tokenizer
+ label="Tags"
+ searchSource={emptySource}
+ value={[]}
+ onChange={() => {}}
+ hasCreate
+ debounceMs={0}
+ />
+ </InternationalizationProvider>,
);
const input = screen.getByRole('combobox');
await act(async () => {
@@ -1059,7 +1077,7 @@ describe('Tokenizer', () => {
});
fireEvent.click(screen.getByText('Create "new-tag"'));
await waitFor(() => {
- expect(politeRegion()).toHaveTextContent('Added new-tag');
+ expect(politeRegion()?.textContent).toBe('Ajouté : new-tag');
});
});
diff --git a/packages/core/src/Tokenizer/Tokenizer.tsx b/packages/core/src/Tokenizer/Tokenizer.tsx
index b33ef271ca..2f825b8fe7 100644
--- a/packages/core/src/Tokenizer/Tokenizer.tsx
+++ b/packages/core/src/Tokenizer/Tokenizer.tsx
@@ -600,7 +600,7 @@ export function Tokenizer<T extends SearchableItem>({
const realItem = base as T;
const newItems = [...value, realItem];
onChange(newItems, {item: realItem, type: 'create'});
- announce(`Added ${createdValue}`);
+ announce(t('@astryx.tokenizer.tokenAdded', {label: createdValue}));
return;
}
@@ -609,9 +609,9 @@ export function Tokenizer<T extends SearchableItem>({
}
const newItems = [...value, item];
onChange(newItems, {item, type: 'add'});
- announce(`Added ${item.label}`);
+ announce(t('@astryx.tokenizer.tokenAdded', {label: item.label}));
},
- [value, onChange, isAtMax, selectedIds, hasCreate, announce],
+ [value, onChange, isAtMax, selectedIds, hasCreate, announce, t],
);
// Handle removing an item. Single removal path: both Backspace on an empty
@@ -621,10 +621,10 @@ export function Tokenizer<T extends SearchableItem>({
(item: T) => {
const newItems = value.filter(v => v.id !== item.id);
onChange(newItems, {item, type: 'remove'});
- announce(`Removed ${item.label}`);
+ announce(t('@astryx.tokenizer.tokenRemoved', {label: item.label}));
inputRef.current?.focus();
},
- [value, onChange, announce],
+ [value, onChange, announce, t],
);
// Handle clearing all items
diff --git a/packages/core/src/Typeahead/BaseTypeahead.tsx b/packages/core/src/Typeahead/BaseTypeahead.tsx
index fc0f840356..e96f03250d 100644
--- a/packages/core/src/Typeahead/BaseTypeahead.tsx
+++ b/packages/core/src/Typeahead/BaseTypeahead.tsx
@@ -449,7 +449,7 @@ export const BaseTypeahead = function BaseTypeahead<T extends SearchableItem>({
announce(
shown.length === 0
? emptySearchResultsText
- : `${shown.length} ${shown.length === 1 ? 'result' : 'results'}`,
+ : t('@astryx.typeahead.resultCount', {count: shown.length}),
);
}
} catch {
@@ -464,7 +464,14 @@ export const BaseTypeahead = function BaseTypeahead<T extends SearchableItem>({
}
}
},
- [searchSource, maxMenuItems, showLayer, announce, emptySearchResultsText],
+ [
+ searchSource,
+ maxMenuItems,
+ showLayer,
+ announce,
+ emptySearchResultsText,
+ t,
+ ],
);
// Perform bootstrap
diff --git a/packages/core/src/Typeahead/Typeahead.test.tsx b/packages/core/src/Typeahead/Typeahead.test.tsx
index e37f349de1..48e668ea54 100644
--- a/packages/core/src/Typeahead/Typeahead.test.tsx
+++ b/packages/core/src/Typeahead/Typeahead.test.tsx
@@ -23,6 +23,7 @@ import userEvent from '@testing-library/user-event';
import {Typeahead} from './Typeahead';
import {BaseTypeahead} from './BaseTypeahead';
import type {SearchSource, SearchableItem} from './types';
+import {InternationalizationProvider} from '../i18n';
// Store original matches to restore later
const originalMatches = HTMLElement.prototype.matches;
@@ -132,21 +133,94 @@ describe('BaseTypeahead', () => {
it('announces the result count to a live region (comboboxes-6)', async () => {
render(
- <BaseTypeahead
- searchSource={fruitSource}
- value={null}
- onChange={() => {}}
- debounceMs={0}
- />,
+ <InternationalizationProvider
+ locale="fr"
+ overrides={{
+ fr: {
+ '@astryx.typeahead.resultCount':
+ '{count, number} {count, plural, one {résultat} other {résultats}}',
+ },
+ }}>
+ <BaseTypeahead
+ searchSource={fruitSource}
+ value={null}
+ onChange={() => {}}
+ debounceMs={0}
+ />
+ </InternationalizationProvider>,
);
const input = screen.getByRole('combobox');
+ // "Ap" matches Apple only — the singular ICU branch.
fireEvent.change(input, {target: {value: 'Ap'}});
await waitFor(() => {
const region = document.querySelector(
'[data-astryx-live-region="polite"]',
);
- expect(region?.textContent).toMatch(/\d+ results?/);
+ // Exact, so the plural branch ("1 résultats") would fail.
+ expect(region?.textContent).toBe('1 résultat');
+ });
+ });
+
+ it('announces the plural result count', async () => {
+ render(
+ <InternationalizationProvider
+ locale="fr"
+ overrides={{
+ fr: {
+ '@astryx.typeahead.resultCount':
+ '{count, number} {count, plural, one {résultat} other {résultats}}',
+ },
+ }}>
+ <BaseTypeahead
+ searchSource={fruitSource}
+ value={null}
+ onChange={() => {}}
+ debounceMs={0}
+ />
+ </InternationalizationProvider>,
+ );
+ const input = screen.getByRole('combobox');
+ // "err" matches Cherry and Elderberry.
+ fireEvent.change(input, {target: {value: 'err'}});
+
+ await waitFor(() => {
+ const region = document.querySelector(
+ '[data-astryx-live-region="polite"]',
+ );
+ expect(region?.textContent).toBe('2 résultats');
+ });
+ });
+
+ it('speaks the result count from a provider catalog', async () => {
+ render(
+ <InternationalizationProvider
+ locale="fr"
+ messages={{
+ fr: {
+ '@astryx.typeahead.resultCount': {
+ defaultMessage:
+ '{count, number} {count, plural, one {résultat} other {résultats}}',
+ },
+ },
+ }}>
+ <BaseTypeahead
+ searchSource={fruitSource}
+ value={null}
+ onChange={() => {}}
+ debounceMs={0}
+ />
+ </InternationalizationProvider>,
+ );
+ const input = screen.getByRole('combobox');
+ fireEvent.change(input, {target: {value: 'err'}});
+
+ await waitFor(() => {
+ const region = document.querySelector(
+ '[data-astryx-live-region="polite"]',
+ );
+ // Same key through the catalog path rather than `overrides`.
+ expect(region?.textContent).toBe('2 résultats');
});
});