Skip to content

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

TypeScript

fix(FileInput): every rejected file is named in the status message (#9043)

Cindy Zhang5b5ae2d790ee
diff --git a/.changeset/fileinput-every-rejection.md b/.changeset/fileinput-every-rejection.md
new file mode 100644
index 0000000000..bbd5f9bb6b
--- /dev/null
+++ b/.changeset/fileinput-every-rejection.md
@@ -0,0 +1,7 @@
+---
+'@astryxdesign/core': patch
+---
+
+[fix] When several picked or dropped files break `accept` or `maxSize`, `FileInput` names every rejected file and why in its status message, not only the first (WCAG 2.2 SC 3.3.1). The messages are listed in the active locale. Going over `maxFiles` still reports the limit, "Maximum N files allowed".
+
+@cixzhang @duytbp
diff --git a/internal/eslint-plugin-astryx/no-raw-intl-locale.js b/internal/eslint-plugin-astryx/no-raw-intl-locale.js
index 52eeb7f172..2f7f0fac6d 100644
--- a/internal/eslint-plugin-astryx/no-raw-intl-locale.js
+++ b/internal/eslint-plugin-astryx/no-raw-intl-locale.js
@@ -120,6 +120,8 @@ const APPROVED_IMPLEMENTATION_FILES = [
// separator and day-period words, read off Intl and parsed back.
'packages/core/src/utils/timeFormat.ts',
'packages/core/src/i18n/useCollator.ts',
+ // Joins several catalog messages into one locale-correct list (INV8).
+ 'packages/core/src/i18n/useListFormatter.ts',
'packages/charts/src/formatters.ts',
];
@@ -136,6 +138,7 @@ const APPROVED_TEST_ORACLE_FILES = [
'packages/core/src/Timestamp/tooltipEntries.test.ts',
'packages/core/src/PowerSearch/formatFilterValue.test.ts',
'packages/core/src/Timestamp/Timestamp.test.tsx',
+ 'packages/core/src/i18n/__tests__/useListFormatter.test.tsx',
];
// These exact helper suites are the public default-behavior oracles. Production
diff --git a/internal/eslint-plugin-astryx/no-raw-intl-locale.test.mjs b/internal/eslint-plugin-astryx/no-raw-intl-locale.test.mjs
index 18fa0b4173..1d09ef1c74 100644
--- a/internal/eslint-plugin-astryx/no-raw-intl-locale.test.mjs
+++ b/internal/eslint-plugin-astryx/no-raw-intl-locale.test.mjs
@@ -34,6 +34,7 @@ const COMPONENT_FILE = 'packages/core/src/Calendar/Calendar.tsx';
const INFRA_FILE = 'packages/core/src/utils/plainDate.ts';
const DATE_PARSER_INFRA_FILE = 'packages/core/src/utils/dateParser.ts';
const COLLATOR_INFRA_FILE = 'packages/core/src/i18n/useCollator.ts';
+const LIST_FORMATTER_INFRA_FILE = 'packages/core/src/i18n/useListFormatter.ts';
const RELATIVE_TIME_INFRA_FILE =
'packages/core/src/Timestamp/formatRelativeTime.ts';
const NUMBER_PARSER_INFRA_FILE =
@@ -131,6 +132,10 @@ tester.run('no-raw-intl-locale', rule, {
code: `new Intl.Collator(locale, options);`,
filename: COLLATOR_INFRA_FILE,
},
+ {
+ code: `new Intl.ListFormat(locale, {type: 'unit', style: 'short'});`,
+ filename: LIST_FORMATTER_INFRA_FILE,
+ },
{
code: `new Intl.RelativeTimeFormat(locale, {style: 'narrow'});`,
filename: RELATIVE_TIME_INFRA_FILE,
@@ -481,6 +486,11 @@ tester.run('no-raw-intl-locale', rule, {
filename: COLLATOR_INFRA_FILE,
errors: [navigatorLocale],
},
+ {
+ code: `new Intl.ListFormat(navigator.language);`,
+ filename: LIST_FORMATTER_INFRA_FILE,
+ errors: [navigatorLocale],
+ },
// -- New in this policy: navigator.language/languages is banned in ANY
// position, not only as an Intl/locale-method argument. --
diff --git a/packages/core/src/FileInput/FileInput.test.tsx b/packages/core/src/FileInput/FileInput.test.tsx
index 1e97fe8c4a..445ef5aa7f 100644
--- a/packages/core/src/FileInput/FileInput.test.tsx
+++ b/packages/core/src/FileInput/FileInput.test.tsx
@@ -496,6 +496,74 @@ describe('FileInput', () => {
expect(politeRegion()?.textContent ?? '').toBe('');
});
+ it('identifies every rejected file in one status message (WCAG 3.3.1)', async () => {
+ const onChange = vi.fn();
+ render(
+ <FileInput
+ label="Reports"
+ value={null}
+ onChange={onChange}
+ isMultiple
+ accept=".pdf"
+ maxSize={1024}
+ />,
+ );
+ fireEvent.change(fileInputEl(), {
+ target: {
+ files: [
+ createFile('photo.png', 100),
+ createFile('large.pdf', 4096),
+ createFile('small.pdf', 100),
+ ],
+ },
+ });
+ await waitFor(() => {
+ const status = document.querySelector('.astryx-field-status');
+ expect(status).toHaveTextContent(
+ '"photo.png" is not an accepted file type',
+ );
+ expect(status).toHaveTextContent('"large.pdf" exceeds 1.0 KB limit');
+ });
+ // The valid file is still accepted.
+ expect(onChange).toHaveBeenCalledWith([
+ expect.objectContaining({name: 'small.pdf'}),
+ ]);
+ });
+
+ it('separates the rejected files in a locale whose unit list would run them together', async () => {
+ render(
+ <InternationalizationProvider
+ locale="zh-CN"
+ overrides={{
+ 'zh-CN': {
+ '@astryx.fileInput.errorInvalidType': '“{fileName}”类型不受支持',
+ '@astryx.fileInput.errorMaxSize': '“{fileName}”超过 {maxSize}',
+ },
+ }}>
+ <FileInput
+ label="报告"
+ value={null}
+ onChange={() => {}}
+ isMultiple
+ accept=".pdf"
+ maxSize={1024}
+ />
+ </InternationalizationProvider>,
+ );
+ fireEvent.change(fileInputEl(), {
+ target: {
+ files: [createFile('photo.png', 100), createFile('large.pdf', 4096)],
+ },
+ });
+ await waitFor(() => {
+ const status = document.querySelector('.astryx-field-status');
+ // The two messages are separated (、), not run together.
+ expect(status?.textContent).toMatch(
+ /“photo\.png”类型不受支持、“large\.pdf”超过 /,
+ );
+ });
+ });
+
it('announces a validation error exactly once across live regions', async () => {
render(
<FileInput
diff --git a/packages/core/src/FileInput/FileInput.tsx b/packages/core/src/FileInput/FileInput.tsx
index 25a8c59502..ebd0921dc3 100644
--- a/packages/core/src/FileInput/FileInput.tsx
+++ b/packages/core/src/FileInput/FileInput.tsx
@@ -68,6 +68,7 @@ import {useTranslator} from '../i18n';
import type {TranslatorFn} from '../i18n';
import {useMergedRefs} from '../hooks/useMergedRefs';
+import {useListFormatter} from '../i18n/useListFormatter';
import {useResolvedRequired} from '../hooks/useResolvedRequired';
function formatFileSize(bytes: number, t: TranslatorFn): string {
if (bytes < 1024) {
@@ -492,6 +493,7 @@ export function FileInput({
const containerRef = useRef<HTMLDivElement | null>(null);
const [isDragOver, setIsDragOver] = useState(false);
const [validationError, setValidationError] = useState<string | null>(null);
+ const formatList = useListFormatter();
const [, startTransition] = useTransition();
const [optimisticValue, setOptimisticValue] = useOptimistic(value);
const isBusy = isLoading || optimisticValue !== value;
@@ -583,7 +585,9 @@ export function FileInput({
);
if (errors.length > 0) {
- setValidationError(errors[0]);
+ // Every rejected file is identified, in one status message
+ // (WCAG 3.3.1), joined as a list in the active locale.
+ setValidationError(formatList(errors));
} else {
setValidationError(null);
}
@@ -628,6 +632,7 @@ export function FileInput({
setOptimisticValue,
announce,
t,
+ formatList,
],
);
diff --git a/packages/core/src/i18n/__tests__/useListFormatter.test.tsx b/packages/core/src/i18n/__tests__/useListFormatter.test.tsx
new file mode 100644
index 0000000000..f9226e1e23
--- /dev/null
+++ b/packages/core/src/i18n/__tests__/useListFormatter.test.tsx
@@ -0,0 +1,58 @@
+// Copyright (c) Meta Platforms, Inc. and affiliates.
+
+/**
+ * @file useListFormatter.test.tsx
+ * @input packages/core/src/i18n/useListFormatter.ts, InternationalizationProvider
+ * @output Unit tests for the internal provider-aware list formatter
+ * @position Colocated tests; the platform Intl.ListFormat is the independent
+ * oracle for each locale.
+ */
+
+import type {ReactNode} from 'react';
+import {describe, expect, test} from 'vitest';
+import {renderHook} from '@testing-library/react';
+import {useListFormatter} from '../useListFormatter';
+import {InternationalizationProvider} from '../InternationalizationProvider';
+
+const items = ['"a.png" is not an accepted file type', '"b.pdf" exceeds 1 MB'];
+
+function wrapperFor(locale: string) {
+ return ({children}: {children: ReactNode}) => (
+ <InternationalizationProvider locale={locale}>
+ {children}
+ </InternationalizationProvider>
+ );
+}
+
+const oracle = (locale: string, list: string[]) =>
+ new Intl.ListFormat(locale, {type: 'conjunction', style: 'narrow'}).format(
+ list,
+ );
+
+describe('useListFormatter', () => {
+ test('joins with the en fallback when rendered without a provider', () => {
+ const {result} = renderHook(() => useListFormatter());
+ expect(result.current(items)).toBe(oracle('en', items));
+ });
+
+ test('joins in the provider locale', () => {
+ const three = ['un', 'deux', 'trois'];
+ const {result: zh} = renderHook(() => useListFormatter(), {
+ wrapper: wrapperFor('zh-CN'),
+ });
+ const {result: en} = renderHook(() => useListFormatter(), {
+ wrapper: wrapperFor('en'),
+ });
+ expect(zh.current(three)).toBe(oracle('zh-CN', three));
+ expect(zh.current(three)).not.toBe(en.current(three));
+ });
+
+ test('keeps the same function while the locale is unchanged', () => {
+ const {result, rerender} = renderHook(() => useListFormatter(), {
+ wrapper: wrapperFor('de-DE'),
+ });
+ const first = result.current;
+ rerender();
+ expect(result.current).toBe(first);
+ });
+});
diff --git a/packages/core/src/i18n/useListFormatter.ts b/packages/core/src/i18n/useListFormatter.ts
new file mode 100644
index 0000000000..74fbd2a358
--- /dev/null
+++ b/packages/core/src/i18n/useListFormatter.ts
@@ -0,0 +1,42 @@
+// Copyright (c) Meta Platforms, Inc. and affiliates.
+
+'use client';
+
+/**
+ * @file useListFormatter.ts
+ * @input InternationalizationContext (via use())
+ * @output A memoized function that joins strings as a list in the active locale
+ * @position Internal provider-aware list-formatting hook
+ * (architecture:internationalization INV8). Components that show several
+ * catalog messages as one string join them here rather than at the call
+ * site (INV1a). Not exported from the i18n barrel. Raw Intl.ListFormat
+ * construction stays centralized in this hook.
+ *
+ * Falls back to `'en'` when called outside a provider, matching the
+ * useTranslator/useCollator fallback.
+ *
+ * SYNC: When modified, update:
+ * - /packages/core/src/i18n/__tests__/useListFormatter.test.tsx
+ * - /internal/eslint-plugin-astryx/no-raw-intl-locale.js
+ */
+
+import {use, useMemo} from 'react';
+import {InternationalizationContext} from './InternationalizationContext';
+
+/**
+ * Returns a function that joins items as a narrow conjunction list (`a, b, c`
+ * in English) for the active provider locale, memoized while the locale is
+ * unchanged. The narrow conjunction separates items in every shipped locale,
+ * including whole sentences, where a unit list runs them together in some
+ * (no separator in zh-CN, only a space in ja-JP).
+ */
+export function useListFormatter(): (items: ReadonlyArray<string>) => string {
+ const ctx = use(InternationalizationContext);
+ return useMemo(() => {
+ const format = new Intl.ListFormat(ctx.locale, {
+ type: 'conjunction',
+ style: 'narrow',
+ });
+ return (items: ReadonlyArray<string>) => format.format(items);
+ }, [ctx.locale]);
+}