Skip to content

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

TypeScript

feat(core): add XDSFileInput component (#2184)

Andrey Goder407cee64e862
diff --git a/apps/storybook/stories/FileInput.stories.tsx b/apps/storybook/stories/FileInput.stories.tsx
new file mode 100644
index 0000000000..b55201e123
--- /dev/null
+++ b/apps/storybook/stories/FileInput.stories.tsx
@@ -0,0 +1,264 @@
+// Copyright (c) Meta Platforms, Inc. and affiliates.
+
+import {useState} from 'react';
+import type {Meta, StoryObj} from '@storybook/react';
+import {XDSFileInput} from '@xds/core/FileInput';
+
+const meta: Meta<typeof XDSFileInput> = {
+ title: 'Core/Inputs/FileInput',
+ component: XDSFileInput,
+ tags: ['autodocs'],
+ argTypes: {
+ label: {
+ control: 'text',
+ description: 'Label text (required)',
+ },
+ isLabelHidden: {
+ control: 'boolean',
+ description:
+ 'Visually hide the label (still accessible to screen readers)',
+ },
+ placeholder: {
+ control: 'text',
+ description: 'Placeholder text',
+ },
+ description: {
+ control: 'text',
+ description: 'Description text displayed between the label and input',
+ },
+ accept: {
+ control: 'text',
+ description: 'Accepted file types (e.g. "image/*", ".pdf,.doc")',
+ },
+ isMultiple: {
+ control: 'boolean',
+ description: 'Whether multiple files can be selected',
+ },
+ isOptional: {
+ control: 'boolean',
+ description:
+ 'Whether the field is optional (mutually exclusive with isRequired)',
+ },
+ isRequired: {
+ control: 'boolean',
+ description:
+ 'Whether the field is required (mutually exclusive with isOptional)',
+ },
+ isDisabled: {
+ control: 'boolean',
+ description: 'Whether the input is disabled',
+ },
+ isLoading: {
+ control: 'boolean',
+ description: 'Whether the input is in a loading state',
+ },
+ mode: {
+ control: 'select',
+ options: ['input', 'dropzone'],
+ description: 'Visual mode: compact input or drag-and-drop dropzone',
+ },
+ status: {
+ control: 'object',
+ description:
+ 'Status indicator with type (warning/error/success) and optional message',
+ },
+ labelTooltip: {
+ control: 'text',
+ description:
+ 'Tooltip text to display in an info icon at the end of the label',
+ },
+ },
+};
+
+export default meta;
+type Story = StoryObj<typeof XDSFileInput>;
+
+export const Default: Story = {
+ render: args => {
+ const [value, setValue] = useState<File | File[] | null>(null);
+ return <XDSFileInput {...args} value={value} onChange={setValue} />;
+ },
+ args: {
+ label: 'Upload file',
+ placeholder: 'Drag files here or click to browse',
+ },
+};
+
+export const WithDescription: Story = {
+ render: args => {
+ const [value, setValue] = useState<File | File[] | null>(null);
+ return <XDSFileInput {...args} value={value} onChange={setValue} />;
+ },
+ args: {
+ label: 'Resume',
+ description: 'Upload your resume in PDF or Word format. Max 5MB.',
+ accept: '.pdf,.doc,.docx',
+ },
+};
+
+export const MultipleFiles: Story = {
+ render: args => {
+ const [value, setValue] = useState<File | File[] | null>(null);
+ return <XDSFileInput {...args} value={value} onChange={setValue} />;
+ },
+ args: {
+ label: 'Attachments',
+ isMultiple: true,
+ description: 'Upload up to 10 files. Max 5MB each.',
+ maxFiles: 10,
+ maxSize: 5 * 1024 * 1024,
+ },
+};
+
+export const ImagesOnly: Story = {
+ render: args => {
+ const [value, setValue] = useState<File | File[] | null>(null);
+ return <XDSFileInput {...args} value={value} onChange={setValue} />;
+ },
+ args: {
+ label: 'Profile photo',
+ accept: 'image/png,image/jpeg',
+ description: 'PNG or JPEG, max 2MB.',
+ maxSize: 2 * 1024 * 1024,
+ },
+};
+
+export const DropzoneMode: Story = {
+ render: args => {
+ const [value, setValue] = useState<File | File[] | null>(null);
+ return <XDSFileInput {...args} value={value} onChange={setValue} />;
+ },
+ args: {
+ label: 'Upload files',
+ mode: 'dropzone',
+ placeholder: 'Drag files here or click to browse',
+ },
+};
+
+export const Required: Story = {
+ render: args => {
+ const [value, setValue] = useState<File | File[] | null>(null);
+ return <XDSFileInput {...args} value={value} onChange={setValue} />;
+ },
+ args: {
+ label: 'Supporting document',
+ isRequired: true,
+ },
+};
+
+export const Optional: Story = {
+ render: args => {
+ const [value, setValue] = useState<File | File[] | null>(null);
+ return <XDSFileInput {...args} value={value} onChange={setValue} />;
+ },
+ args: {
+ label: 'Cover letter',
+ isOptional: true,
+ },
+};
+
+export const Disabled: Story = {
+ render: args => {
+ const [value, setValue] = useState<File | File[] | null>(null);
+ return <XDSFileInput {...args} value={value} onChange={setValue} />;
+ },
+ args: {
+ label: 'Upload locked',
+ isDisabled: true,
+ placeholder: 'Upload is currently disabled',
+ },
+};
+
+export const Loading: Story = {
+ render: args => {
+ const [value, setValue] = useState<File | File[] | null>(null);
+ return <XDSFileInput {...args} value={value} onChange={setValue} />;
+ },
+ args: {
+ label: 'Uploading...',
+ isLoading: true,
+ },
+};
+
+export const WithErrorStatus: Story = {
+ render: args => {
+ const [value, setValue] = useState<File | File[] | null>(null);
+ return <XDSFileInput {...args} value={value} onChange={setValue} />;
+ },
+ args: {
+ label: 'Upload document',
+ status: {type: 'error', message: 'File must be under 10MB'},
+ },
+};
+
+export const WithSuccessStatus: Story = {
+ render: args => {
+ const [value, setValue] = useState<File | File[] | null>(null);
+ return <XDSFileInput {...args} value={value} onChange={setValue} />;
+ },
+ args: {
+ label: 'Upload document',
+ status: {type: 'success', message: 'File uploaded successfully'},
+ },
+};
+
+export const WithTooltip: Story = {
+ render: args => {
+ const [value, setValue] = useState<File | File[] | null>(null);
+ return <XDSFileInput {...args} value={value} onChange={setValue} />;
+ },
+ args: {
+ label: 'Tax documents',
+ labelTooltip: 'Upload W-2 forms, 1099s, or other tax-related documents.',
+ },
+};
+
+export const AllVariations: Story = {
+ render: () => {
+ const [v1, setV1] = useState<File | File[] | null>(null);
+ const [v2, setV2] = useState<File | File[] | null>(null);
+ const [v3, setV3] = useState<File | File[] | null>(null);
+ const [v4, setV4] = useState<File | File[] | null>(null);
+ const [v5, setV5] = useState<File | File[] | null>(null);
+ return (
+ <div
+ style={{
+ display: 'flex',
+ flexDirection: 'column',
+ gap: '24px',
+ maxWidth: '400px',
+ }}>
+ <XDSFileInput
+ label="Default (input mode)"
+ value={v1}
+ onChange={setV1}
+ />
+ <XDSFileInput
+ label="Dropzone with constraints"
+ value={v2}
+ onChange={setV2}
+ mode="dropzone"
+ isMultiple
+ accept="image/*"
+ maxSize={5 * 1024 * 1024}
+ maxFiles={5}
+ description="Up to 5 images, max 5MB each"
+ />
+ <XDSFileInput
+ label="Dropzone mode"
+ value={v3}
+ onChange={setV3}
+ mode="dropzone"
+ placeholder="Drag files here or click to browse"
+ />
+ <XDSFileInput label="Disabled" value={v4} onChange={setV4} isDisabled />
+ <XDSFileInput
+ label="With error"
+ value={v5}
+ onChange={setV5}
+ status={{type: 'error', message: 'Please upload a valid file'}}
+ />
+ </div>
+ );
+ },
+};
diff --git a/packages/cli/templates/blocks/components/FileInput/FileInputShowcase.doc.mjs b/packages/cli/templates/blocks/components/FileInput/FileInputShowcase.doc.mjs
new file mode 100644
index 0000000000..5e0ff7c72c
--- /dev/null
+++ b/packages/cli/templates/blocks/components/FileInput/FileInputShowcase.doc.mjs
@@ -0,0 +1,11 @@
+// Copyright (c) Meta Platforms, Inc. and affiliates.
+
+export const doc = {
+ type: 'block',
+ exampleFor: 'FileInput',
+ name: 'FileInput',
+ isReady: true,
+ aspectRatio: 16 / 9,
+ isShowcase: true,
+ componentsUsed: ['FileInput'],
+};
diff --git a/packages/cli/templates/blocks/components/FileInput/FileInputShowcase.tsx b/packages/cli/templates/blocks/components/FileInput/FileInputShowcase.tsx
new file mode 100644
index 0000000000..cf83370917
--- /dev/null
+++ b/packages/cli/templates/blocks/components/FileInput/FileInputShowcase.tsx
@@ -0,0 +1,18 @@
+// Copyright (c) Meta Platforms, Inc. and affiliates.
+
+'use client';
+
+import {XDSFileInput} from '@xds/core/FileInput';
+
+export default function FileInputShowcase() {
+ return (
+ <div style={{width: 350}}>
+ <XDSFileInput
+ label="Upload file"
+ value={null}
+ onChange={() => {}}
+ placeholder="Drag files here or click to browse"
+ />
+ </div>
+ );
+}
diff --git a/packages/core/package.json b/packages/core/package.json
index 7fdd2e588a..9e33bd647a 100644
--- a/packages/core/package.json
+++ b/packages/core/package.json
@@ -241,6 +241,12 @@
"import": "./dist/Field/index.mjs",
"require": "./dist/Field/index.js"
},
+ "./FileInput": {
+ "source": "./src/FileInput/index.ts",
+ "types": "./dist/FileInput/index.d.ts",
+ "import": "./dist/FileInput/index.mjs",
+ "require": "./dist/FileInput/index.js"
+ },
"./FormLayout": {
"source": "./src/FormLayout/index.ts",
"types": "./dist/FormLayout/index.d.ts",
diff --git a/packages/core/src/FileInput/FileInput.doc.mjs b/packages/core/src/FileInput/FileInput.doc.mjs
new file mode 100644
index 0000000000..e520cc4751
--- /dev/null
+++ b/packages/core/src/FileInput/FileInput.doc.mjs
@@ -0,0 +1,300 @@
+// Copyright (c) Meta Platforms, Inc. and affiliates.
+
+/** @type {import('../docs-types').ComponentDoc} */
+
+export const docs = {
+ name: 'FileInput',
+ keywords: ["fileinput","file","upload","drag","drop","dropzone","attachment","browse"],
+ props: [
+ {
+ name: 'label',
+ type: 'string',
+ description:
+ 'Accessible label for the file input.',
+ required: true,
+ },
+ {
+ name: 'value',
+ type: 'File | File[] | null',
+ description: 'Currently selected file(s). Controlled component.',
+ required: true,
+ },
+ {
+ name: 'onChange',
+ type: '(files: File | File[] | null) => void',
+ description: 'Callback fired when files are selected or removed.',
+ required: true,
+ },
+ {
+ name: 'onChangeAction',
+ type: '(files: File | File[] | null) => Promise<void>',
+ description:
+ 'Async change action (React 19 transitions pattern). Use for immediate upload on file selection.',
+ },
+ {
+ name: 'accept',
+ type: 'string',
+ description:
+ 'Accepted file types. Uses the HTML accept attribute format (e.g. "image/*", ".pdf,.doc").',
+ },
+ {
+ name: 'isMultiple',
+ type: 'boolean',
+ description: 'Whether multiple files can be selected. When true, value and onChange use File[] instead of File.',
+ default: 'false',
+ },
+ {
+ name: 'maxSize',
+ type: 'number',
+ description: 'Maximum file size in bytes. Files exceeding this are rejected with an error status.',
+ },
+ {
+ name: 'maxFiles',
+ type: 'number',
+ description: 'Maximum number of files (only applies when isMultiple is true).',
+ },
+ {
+ name: 'isLabelHidden',
+ type: 'boolean',
+ description:
+ 'Visually hides the label while keeping it accessible to screen readers.',
+ default: 'false',
+ },
+ {
+ name: 'description',
+ type: 'string',
+ description: 'Description text displayed between the label and input.',
+ },
+ {
+ name: 'isOptional',
+ type: 'boolean',
+ description:
+ 'Displays an "Optional" indicator next to the label. Mutually exclusive with isRequired.',
+ default: 'false',
+ },
+ {
+ name: 'isRequired',
+ type: 'boolean',
+ description:
+ 'Displays a "Required" indicator next to the label and sets aria-required. Mutually exclusive with isOptional.',
+ default: 'false',
+ },
+ {
+ name: 'isDisabled',
+ type: 'boolean',
+ description:
+ 'Disables the input, preventing interaction and dimming the element.',
+ default: 'false',
+ },
+ {
+ name: 'isLoading',
+ type: 'boolean',
+ description:
+ 'Puts the input in a loading state, showing a spinner and setting aria-busy.',
+ default: 'false',
+ },
+ {
+ name: 'placeholder',
+ type: 'string',
+ description: 'Placeholder text shown when no file is selected.',
+ default: '"Choose file" or "Choose files"',
+ },
+ {
+ name: 'mode',
+ type: "'input' | 'dropzone'",
+ description: "Visual mode. 'input' is a compact inline style; 'dropzone' is a larger area with drag-and-drop support.",
+ default: "'input'",
+ },
+ {
+ name: 'status',
+ type: "{type: 'error' | 'warning' | 'success', message?: string}",
+ description:
+ 'Validation status — applies a colored border. If message is provided, displays a floating message below the input. Error type also sets aria-invalid.',
+ },
+ {
+ name: 'labelTooltip',
+ type: 'string',
+ description:
+ 'Tooltip text displayed in an info icon at the end of the label.',
+ },
+ ],
+ theming: {
+ targets: [
+ {className: 'xds-file-input', visualProps: ['mode', 'status']},
+ ],
+ },
+ usage: {
+ description:
+ 'FileInput provides file upload with optional drag-and-drop support. Use it for single or multiple file selection with built-in validation for file type, size, and count. Pair with validation status for upload feedback.',
+ bestPractices: [
+ {guidance: true, description: 'Always specify an accept prop to guide users toward valid file types.'},
+ {guidance: true, description: 'Use maxSize and maxFiles to prevent oversized uploads — the component handles validation and error display automatically.'},
+ {guidance: true, description: 'Add a description to communicate constraints like file size limits or accepted formats.'},
+ {guidance: true, description: 'Use onChangeAction for immediate upload workflows that benefit from optimistic UI.'},
+ {guidance: false, description: "Don't use FileInput for directory or folder uploads — that is not supported in v1."},
+ {guidance: false, description: "Don't avoid dropzone mode unless space is very constrained — drag-and-drop is the expected interaction for file uploads."},
+ ],
+ anatomy: [
+ {name: 'Label', required: true, description: 'Text that identifies the field. Always rendered for accessibility even when visually hidden.'},
+ {name: 'Description', required: false, description: 'Helper text between the label and the drop zone explaining accepted formats or size limits.'},
+ {name: 'Drop zone', required: true, description: 'The clickable area for file selection. In dropzone mode, also accepts dragged files.'},
+ {name: 'Upload icon', required: false, description: 'An arrow icon in the drop zone hinting at the upload action.'},
+ {name: 'Placeholder', required: false, description: 'Hint text shown when no files are selected.'},
+ {name: 'File name display', required: false, description: 'Shows the name(s) of selected files.'},
+ {name: 'Clear button', required: false, description: 'A close button that removes selected files and returns focus to the input.'},
+ {name: 'Spinner', required: false, description: 'Loading indicator that appears during async upload actions.'},
+ {name: 'Status message', required: false, description: 'Validation feedback showing error, warning, or success with a message.'},
+ ],
+ },
+};
+
+/** @type {import('../docs-types').ComponentDoc} */
+export const docsZh = {
+ name: 'FileInput',
+ props: [
+ {
+ name: 'label',
+ type: 'string',
+ description: '文件输入框的无障碍标签。',
+ required: true,
+ },
+ {
+ name: 'value',
+ type: 'File | File[] | null',
+ description: '当前选中的文件。受控组件。',
+ required: true,
+ },
+ {
+ name: 'onChange',
+ type: '(files: File | File[] | null) => void',
+ description: '文件选择或移除时触发的回调。',
+ required: true,
+ },
+ {
+ name: 'accept',
+ type: 'string',
+ description: '接受的文件类型。使用 HTML accept 属性格式。',
+ },
+ {
+ name: 'isMultiple',
+ type: 'boolean',
+ description: '是否可以选择多个文件。',
+ default: 'false',
+ },
+ {
+ name: 'maxSize',
+ type: 'number',
+ description: '最大文件大小(字节)。超过此限制的文件将被拒绝。',
+ },
+ {
+ name: 'maxFiles',
+ type: 'number',
+ description: '最大文件数(仅在 isMultiple 为 true 时适用)。',
+ },
+ {
+ name: 'isLabelHidden',
+ type: 'boolean',
+ description: '视觉上隐藏标签,保持屏幕阅读器可访问。',
+ default: 'false',
+ },
+ {
+ name: 'description',
+ type: 'string',
+ description: '显示在标签和输入框之间的描述文本。',
+ },
+ {
+ name: 'isDisabled',
+ type: 'boolean',
+ description: '禁用输入框,阻止交互并使元素变暗。',
+ default: 'false',
+ },
+ {
+ name: 'isLoading',
+ type: 'boolean',
+ description: '加载状态,显示旋转器并设置 aria-busy。',
+ default: 'false',
+ },
+ {
+ name: 'placeholder',
+ type: 'string',
+ description: '未选择文件时显示的占位符文本。',
+ },
+ {
+ name: 'mode',
+ type: "'input' | 'dropzone'",
+ description: "视觉模式。'input' 为紧凑内联样式;'dropzone' 为支持拖放的较大区域。",
+ default: "'input'",
+ },
+ {
+ name: 'status',
+ type: "{type: 'error' | 'warning' | 'success', message?: string}",
+ description: '验证状态。',
+ },
+ ],
+ theming: {
+ targets: [
+ {className: 'xds-file-input', visualProps: ['mode', 'status']},
+ ],
+ },
+ usage: {
+ description:
+ 'FileInput provides file upload with optional drag-and-drop support. Use it for single or multiple file selection with built-in validation for file type, size, and count. Pair with validation status for upload feedback.',
+ bestPractices: [
+ {guidance: true, description: 'Always specify an accept prop to guide users toward valid file types.'},
+ {guidance: true, description: 'Use maxSize and maxFiles to prevent oversized uploads.'},
+ {guidance: true, description: 'Add a description to communicate constraints.'},
+ {guidance: false, description: "Don't use FileInput for directory uploads."},
+ {guidance: false, description: "Don't use mode='input' unless space is very constrained — dropzone mode provides a better experience."},
+ ],
+ anatomy: [
+ {name: 'Label', required: true, description: 'Text identifying the field.'},
+ {name: 'Drop zone', required: true, description: 'Clickable area for file selection.'},
+ {name: 'Placeholder', required: false, description: 'Hint text when no files selected.'},
+ {name: 'File name display', required: false, description: 'Shows selected file names.'},
+ {name: 'Clear button', required: false, description: 'Removes selected files.'},
+ ],
+ },
+};
+
+/** @type {import('../docs-types').TranslationDoc} */
+export const docsDense = {
+ description: 'File input w/ input/dropzone modes, validation, label, description, status.',
+ usage: {
+ description:
+ 'FileInput provides file upload with optional drag-and-drop support. Use it for single or multiple file selection with built-in validation for file type, size, and count.',
+ bestPractices: [
+ {guidance: true, description: 'Always specify an accept prop to guide users toward valid file types.'},
+ {guidance: true, description: 'Use maxSize and maxFiles to prevent oversized uploads.'},
+ {guidance: true, description: 'Add a description to communicate constraints.'},
+ {guidance: false, description: "Don't use FileInput for directory uploads."},
+ {guidance: false, description: "Don't use mode='input' unless space is very constrained — dropzone mode provides a better experience."},
+ ],
+ anatomy: [
+ {name: 'Label', required: true, description: 'Text identifying the field.'},
+ {name: 'Drop zone', required: true, description: 'Clickable area for file selection.'},
+ {name: 'Placeholder', required: false, description: 'Hint text when no files selected.'},
+ {name: 'File name display', required: false, description: 'Shows selected file names.'},
+ {name: 'Clear button', required: false, description: 'Removes selected files.'},
+ ],
+ },
+ propDescriptions: {
+ label: 'Accessible label for the file input.',
+ value: 'Currently selected file(s). Controlled.',
+ onChange: 'Fired when files are selected or removed.',
+ onChangeAction: 'Async action after onChange. For immediate upload.',
+ accept: 'Accepted file types (HTML accept format).',
+ isMultiple: 'Allow multiple file selection.',
+ maxSize: 'Max file size in bytes. Rejects oversized files.',
+ maxFiles: 'Max file count (isMultiple only).',
+ isLabelHidden: 'Visually hides label; keeps screen reader access.',
+ description: 'Description text between label+input.',
+ isOptional: 'Shows "Optional" indicator.',
+ isRequired: 'Shows "Required" indicator+sets aria-required.',
+ isDisabled: 'Disables input, prevents interaction.',
+ isLoading: 'Loading state w/ spinner+aria-busy.',
+ placeholder: 'Placeholder when no files selected.',
+ mode: "Visual mode: 'input' (compact) or 'dropzone' (drag-and-drop).",
+ status: 'Validation status; colored border. Message floats below.',
+ labelTooltip: 'Tooltip in info icon at label end.',
+ },
+};
diff --git a/packages/core/src/FileInput/XDSFileInput.test.tsx b/packages/core/src/FileInput/XDSFileInput.test.tsx
new file mode 100644
index 0000000000..095f264aa8
--- /dev/null
+++ b/packages/core/src/FileInput/XDSFileInput.test.tsx
@@ -0,0 +1,529 @@
+/**
+ * @file XDSFileInput.test.tsx
+ * @input Uses vitest, @testing-library/react, XDSFileInput component
+ * @output Unit tests for XDSFileInput component behavior
+ * @position Testing; validates XDSFileInput.tsx implementation
+ *
+ * SYNC: When XDSFileInput.tsx changes, update tests to match new behavior
+ */
+
+// Copyright (c) Meta Platforms, Inc. and affiliates.
+
+import {describe, it, expect, vi} from 'vitest';
+import {render, screen, fireEvent} from '@testing-library/react';
+import userEvent from '@testing-library/user-event';
+import {XDSFileInput} from './XDSFileInput';
+
+function createFile(
+ name: string,
+ size: number,
+ type: string = 'text/plain',
+): File {
+ const content = new Uint8Array(size);
+ return new File([content], name, {type});
+}
+
+describe('XDSFileInput', () => {
+ it('renders with label', () => {
+ render(<XDSFileInput label="Resume" value={null} onChange={() => {}} />);
+ expect(screen.getByText('Resume')).toBeInTheDocument();
+ });
+
+ it('renders default placeholder for single file', () => {
+ render(<XDSFileInput label="File" value={null} onChange={() => {}} />);
+ expect(screen.getByText('Choose file')).toBeInTheDocument();
+ });
+
+ it('renders default placeholder for multiple files', () => {
+ render(
+ <XDSFileInput
+ label="Files"
+ value={null}
+ onChange={() => {}}
+ isMultiple
+ />,
+ );
+ expect(screen.getByText('Choose files')).toBeInTheDocument();
+ });
+
+ it('renders custom placeholder', () => {
+ render(
+ <XDSFileInput
+ label="Upload"
+ value={null}
+ onChange={() => {}}
+ placeholder="Drop here"
+ />,
+ );
+ expect(screen.getByText('Drop here')).toBeInTheDocument();
+ });
+
+ it('displays selected file name', () => {
+ const file = createFile('report.pdf', 1024, 'application/pdf');
+ render(<XDSFileInput label="Document" value={file} onChange={() => {}} />);
+ expect(screen.getByText('report.pdf')).toBeInTheDocument();
+ });
+
+ it('displays multiple file names', () => {
+ const files = [createFile('a.txt', 100), createFile('b.txt', 200)];
+ render(
+ <XDSFileInput
+ label="Files"
+ value={files}
+ onChange={() => {}}
+ isMultiple
+ />,
+ );
+ expect(screen.getByText('a.txt, b.txt')).toBeInTheDocument();
+ });
+
+ it('forwards ref to the native input', () => {
+ const ref = vi.fn();
+ render(
+ <XDSFileInput
+ ref={ref}
+ label="Upload"
+ value={null}
+ onChange={() => {}}
+ />,
+ );
+ expect(ref).toHaveBeenCalledWith(expect.any(HTMLInputElement));
+ });
+
+ it('visually hides label when isLabelHidden is true', () => {
+ render(
+ <XDSFileInput
+ label="Upload"
+ isLabelHidden
+ value={null}
+ onChange={() => {}}
+ />,
+ );
+ expect(screen.getByText('Upload')).toBeInTheDocument();
+ });
+
+ it('sets aria-required when isRequired is true', () => {
+ render(
+ <XDSFileInput
+ label="Resume"
+ isRequired
+ value={null}
+ onChange={() => {}}
+ />,
+ );
+ const input = document.querySelector('input[type="file"]')!;
+ expect(input).toHaveAttribute('aria-required', 'true');
+ });
+
+ it('does not set aria-required by default', () => {
+ render(<XDSFileInput label="Resume" value={null} onChange={() => {}} />);
+ const input = document.querySelector('input[type="file"]')!;
+ expect(input).not.toHaveAttribute('aria-required');
+ });
+
+ it('sets disabled attribute when isDisabled is true', () => {
+ render(
+ <XDSFileInput
+ label="Upload"
+ isDisabled
+ value={null}
+ onChange={() => {}}
+ />,
+ );
+ const input = document.querySelector('input[type="file"]')!;
+ expect(input).toBeDisabled();
+ });
+
+ it('sets aria-invalid when status type is error', () => {
+ render(
+ <XDSFileInput
+ label="Upload"
+ value={null}
+ onChange={() => {}}
+ status={{type: 'error', message: 'Something went wrong'}}
+ />,
+ );
+ const input = document.querySelector('input[type="file"]')!;
+ expect(input).toHaveAttribute('aria-invalid', 'true');
+ });
+
+ it('does not set aria-invalid for warning status', () => {
+ render(
+ <XDSFileInput
+ label="Upload"
+ value={null}
+ onChange={() => {}}
+ status={{type: 'warning'}}
+ />,
+ );
+ const input = document.querySelector('input[type="file"]')!;
+ expect(input).not.toHaveAttribute('aria-invalid');
+ });
+
+ it('renders status message when provided', () => {
+ render(
+ <XDSFileInput
+ label="Upload"
+ value={null}
+ onChange={() => {}}
+ status={{type: 'error', message: 'File too large'}}
+ />,
+ );
+ expect(screen.getByText('File too large')).toBeInTheDocument();
+ });
+
+ it('renders description text', () => {
+ render(
+ <XDSFileInput
+ label="Upload"
+ value={null}
+ onChange={() => {}}
+ description="Max 5MB"
+ />,
+ );
+ expect(screen.getByText('Max 5MB')).toBeInTheDocument();
+ });
+
+ describe('file selection via native input', () => {
+ it('calls onChange when a file is selected', () => {
+ const handleChange = vi.fn();
+ render(
+ <XDSFileInput label="Upload" value={null} onChange={handleChange} />,
+ );
+ const input = document.querySelector(
+ 'input[type="file"]',
+ ) as HTMLInputElement;
+ const file = createFile('test.txt', 100);
+ fireEvent.change(input, {target: {files: [file]}});
+ expect(handleChange).toHaveBeenCalledWith(file);
+ });
+
+ it('calls onChange with File[] when isMultiple', () => {
+ const handleChange = vi.fn();
+ render(
+ <XDSFileInput
+ label="Upload"
+ value={null}
+ onChange={handleChange}
+ isMultiple
+ />,
+ );
+ const input = document.querySelector(
+ 'input[type="file"]',
+ ) as HTMLInputElement;
+ const files = [createFile('a.txt', 100), createFile('b.txt', 200)];
+ fireEvent.change(input, {target: {files}});
+ expect(handleChange).toHaveBeenCalledWith(files);
+ });
+
+ it('sets accept attribute on native input', () => {
+ render(
+ <XDSFileInput
+ label="Upload"
+ value={null}
+ onChange={() => {}}
+ accept=".pdf,.doc"
+ />,
+ );
+ const input = document.querySelector(
+ 'input[type="file"]',
+ ) as HTMLInputElement;
+ expect(input).toHaveAttribute('accept', '.pdf,.doc');
+ });
+
+ it('sets multiple attribute when isMultiple', () => {
+ render(
+ <XDSFileInput
+ label="Upload"
+ value={null}
+ onChange={() => {}}
+ isMultiple
+ />,
+ );
+ const input = document.querySelector(
+ 'input[type="file"]',
+ ) as HTMLInputElement;
+ expect(input).toHaveAttribute('multiple');
+ });
+ });
+
+ describe('validation', () => {
+ it('rejects files exceeding maxSize', () => {
+ const handleChange = vi.fn();
+ render(
+ <XDSFileInput
+ label="Upload"
+ value={null}
+ onChange={handleChange}
+ maxSize={1024}
+ />,
+ );
+ const input = document.querySelector(
+ 'input[type="file"]',
+ ) as HTMLInputElement;
+ const largeFile = createFile('big.txt', 2048);
+ fireEvent.change(input, {target: {files: [largeFile]}});
+ expect(handleChange).toHaveBeenCalledWith(null);
+ });
+
+ it('accepts files within maxSize', () => {
+ const handleChange = vi.fn();
+ render(
+ <XDSFileInput
+ label="Upload"
+ value={null}
+ onChange={handleChange}
+ maxSize={1024}
+ />,
+ );
+ const input = document.querySelector(
+ 'input[type="file"]',
+ ) as HTMLInputElement;
+ const file = createFile('small.txt', 512);
+ fireEvent.change(input, {target: {files: [file]}});
+ expect(handleChange).toHaveBeenCalledWith(file);
+ });
+
+ it('limits files to maxFiles', () => {
+ const handleChange = vi.fn();
+ render(
+ <XDSFileInput
+ label="Upload"
+ value={null}
+ onChange={handleChange}
+ isMultiple
+ maxFiles={2}
+ />,
+ );
+ const input = document.querySelector(
+ 'input[type="file"]',
+ ) as HTMLInputElement;
+ const files = [
+ createFile('a.txt', 100),
+ createFile('b.txt', 100),
+ createFile('c.txt', 100),
+ ];
+ fireEvent.change(input, {target: {files}});
+ expect(handleChange).toHaveBeenCalledWith([
+ expect.objectContaining({name: 'a.txt'}),
+ expect.objectContaining({name: 'b.txt'}),
+ ]);
+ });
+
+ it('rejects files with non-matching accept types', () => {
+ const handleChange = vi.fn();
+ render(
+ <XDSFileInput
+ label="Upload"
+ value={null}
+ onChange={handleChange}
+ accept=".pdf"
+ />,
+ );
+ const input = document.querySelector(
+ 'input[type="file"]',
+ ) as HTMLInputElement;
+ const file = createFile('image.png', 100, 'image/png');
+ fireEvent.change(input, {target: {files: [file]}});
+ expect(handleChange).toHaveBeenCalledWith(null);
+ });
+
+ it('accepts files matching wildcard accept types', () => {
+ const handleChange = vi.fn();
+ render(
+ <XDSFileInput
+ label="Upload"
+ value={null}
+ onChange={handleChange}
+ accept="image/*"
+ />,
+ );
+ const input = document.querySelector(
+ 'input[type="file"]',
+ ) as HTMLInputElement;
+ const file = createFile('photo.jpg', 100, 'image/jpeg');
+ fireEvent.change(input, {target: {files: [file]}});
+ expect(handleChange).toHaveBeenCalledWith(file);
+ });
+ });
+
+ describe('clear button', () => {
+ it('shows clear button when files are selected', () => {
+ const file = createFile('test.txt', 100);
+ render(<XDSFileInput label="Upload" value={file} onChange={() => {}} />);
+ expect(
+ screen.getByRole('button', {name: 'Clear Upload'}),
+ ).toBeInTheDocument();
+ });
+
+ it('does not show clear button when no files selected', () => {
+ render(<XDSFileInput label="Upload" value={null} onChange={() => {}} />);
+ expect(
+ screen.queryByRole('button', {name: 'Clear Upload'}),
+ ).not.toBeInTheDocument();
+ });
+
+ it('does not show clear button when disabled', () => {
+ const file = createFile('test.txt', 100);
+ render(
+ <XDSFileInput
+ label="Upload"
+ value={file}
+ onChange={() => {}}
+ isDisabled
+ />,
+ );
+ expect(
+ screen.queryByRole('button', {name: 'Clear Upload'}),
+ ).not.toBeInTheDocument();
+ });
+
+ it('calls onChange with null when clear is clicked', async () => {
+ const user = userEvent.setup();
+ const handleChange = vi.fn();
+ const file = createFile('test.txt', 100);
+ render(
+ <XDSFileInput label="Upload" value={file} onChange={handleChange} />,
+ );
+ await user.click(screen.getByRole('button', {name: 'Clear Upload'}));
+ expect(handleChange).toHaveBeenCalledWith(null);
+ });
+
+ it('does not show clear button during loading', () => {
+ const file = createFile('test.txt', 100);
+ render(
+ <XDSFileInput
+ label="Upload"
+ value={file}
+ onChange={() => {}}
+ isLoading
+ />,
+ );
+ expect(
+ screen.queryByRole('button', {name: 'Clear Upload'}),
+ ).not.toBeInTheDocument();
+ });
+ });
+
+ describe('drag and drop', () => {
+ it('calls onChange when files are dropped in dropzone mode', () => {
+ const handleChange = vi.fn();
+ render(
+ <XDSFileInput
+ label="Upload"
+ value={null}
+ onChange={handleChange}
+ mode="dropzone"
+ />,
+ );
+ const dropzone = screen.getByRole('button', {name: 'Upload'});
+ const file = createFile('dropped.txt', 100);
+ fireEvent.drop(dropzone, {
+ dataTransfer: {files: [file]},
+ });
+ expect(handleChange).toHaveBeenCalledWith(file);
+ });
+
+ it('does not handle drop in input mode', () => {
+ const handleChange = vi.fn();
+ render(
+ <XDSFileInput label="Upload" value={null} onChange={handleChange} />,
+ );
+ const dropzone = screen.getByRole('button', {name: 'Upload'});
+ const file = createFile('dropped.txt', 100);
+ fireEvent.drop(dropzone, {
+ dataTransfer: {files: [file]},
+ });
+ expect(handleChange).not.toHaveBeenCalled();
+ });
+
+ it('does not handle drop when disabled', () => {
+ const handleChange = vi.fn();
+ render(
+ <XDSFileInput
+ label="Upload"
+ value={null}
+ onChange={handleChange}
+ mode="dropzone"
+ isDisabled
+ />,
+ );
+ const dropzone = screen.getByRole('button', {name: 'Upload'});
+ const file = createFile('dropped.txt', 100);
+ fireEvent.drop(dropzone, {
+ dataTransfer: {files: [file]},
+ });
+ expect(handleChange).not.toHaveBeenCalled();
+ });
+ });
+
+ describe('keyboard interaction', () => {
+ it('opens file picker on Enter key', () => {
+ render(<XDSFileInput label="Upload" value={null} onChange={() => {}} />);
+ const dropzone = screen.getByRole('button', {name: 'Upload'});
+ const input = document.querySelector(
+ 'input[type="file"]',
+ ) as HTMLInputElement;
+ const clickSpy = vi.spyOn(input, 'click');
+ fireEvent.keyDown(dropzone, {key: 'Enter'});
+ expect(clickSpy).toHaveBeenCalled();
+ clickSpy.mockRestore();
+ });
+
+ it('opens file picker on Space key', () => {
+ render(<XDSFileInput label="Upload" value={null} onChange={() => {}} />);
+ const dropzone = screen.getByRole('button', {name: 'Upload'});
+ const input = document.querySelector(
+ 'input[type="file"]',
+ ) as HTMLInputElement;
+ const clickSpy = vi.spyOn(input, 'click');
+ fireEvent.keyDown(dropzone, {key: ' '});
+ expect(clickSpy).toHaveBeenCalled();
+ clickSpy.mockRestore();
+ });
+ });
+
+ describe('dropzone mode', () => {
+ it('renders in dropzone mode', () => {
+ render(
+ <XDSFileInput
+ label="Upload"
+ value={null}
+ onChange={() => {}}
+ mode="dropzone"
+ />,
+ );
+ expect(screen.getByText('Choose file')).toBeInTheDocument();
+ });
+
+ it('displays file name in dropzone mode', () => {
+ const file = createFile('doc.pdf', 100, 'application/pdf');
+ render(
+ <XDSFileInput
+ label="Upload"
+ value={file}
+ onChange={() => {}}
+ mode="dropzone"
+ />,
+ );
+ expect(screen.getByText('doc.pdf')).toBeInTheDocument();
+ });
+ });
+
+ describe('data-testid', () => {
+ it('passes data-testid to native input', () => {
+ render(
+ <XDSFileInput
+ label="Upload"
+ value={null}
+ onChange={() => {}}
+ data-testid="file-upload"
+ />,
+ );
+ const input = document.querySelector(
+ 'input[type="file"]',
+ ) as HTMLInputElement;
+ expect(input).toHaveAttribute('data-testid', 'file-upload');
+ });
+ });
+});
diff --git a/packages/core/src/FileInput/XDSFileInput.tsx b/packages/core/src/FileInput/XDSFileInput.tsx
new file mode 100644
index 0000000000..83da0d1f39
--- /dev/null
+++ b/packages/core/src/FileInput/XDSFileInput.tsx
@@ -0,0 +1,734 @@
+// Copyright (c) Meta Platforms, Inc. and affiliates.
+
+'use client';
+
+/**
+ * @file XDSFileInput.tsx
+ * @input Uses React, useId, XDSField, XDSIcon, XDSSpinner
+ * @output Exports XDSFileInput component, XDSFileInputProps, XDSFileInputStatus
+ * @position Core implementation; consumed by index.ts, tested by XDSFileInput.test.tsx
+ *
+ * SYNC: When modified, update these files to stay in sync:
+ * - /packages/core/src/FileInput/FileInput.doc.mjs (props table, features, implementation notes)
+ * - /packages/core/src/FileInput/XDSFileInput.test.tsx (tests for new/changed behavior)
+ * - /packages/core/src/FileInput/index.ts (exports if types change)
+ * - /apps/storybook/stories/FileInput.stories.tsx (storybook stories)
+ * - /packages/cli/templates/blocks/components/FileInput/ (showcase blocks)
+ */
+
+import {
+ useId,
+ useCallback,
+ useRef,
+ useState,
+ useTransition,
+ type DragEvent,
+} from 'react';
+import * as stylex from '@stylexjs/stylex';
+import {
+ colorVars,
+ sizeVars,
+ spacingVars,
+ radiusVars,
+ typographyVars,
+ typeScaleVars,
+ borderVars,
+ durationVars,
+ easeVars,
+} from '../theme/tokens.stylex';
+import {XDSField, type XDSInputStatus, type XDSInputStatusType} from '../Field';
+import {XDSIcon, type XDSIconName} from '../Icon';
+import {XDSSpinner} from '../Spinner';
+
+export type {
+ XDSInputStatus as XDSFileInputStatus,
+ XDSInputStatusType as XDSFileInputStatusType,
+} from '../Field';
+import {xdsClassName, mergeProps} from '../utils';
+import {XDSBaseProps} from '../XDSBaseProps';
+
+function formatFileSize(bytes: number): string {
+ if (bytes < 1024) return `${bytes} B`;
+ if (bytes < 1024 * 1024) return `${(bytes / 1024).toFixed(1)} KB`;
+ return `${(bytes / (1024 * 1024)).toFixed(1)} MB`;
+}
+
+function validateFiles(
+ files: File[],
+ accept: string | undefined,
+ maxSize: number | undefined,
+ maxFiles: number | undefined,
+ isMultiple: boolean,
+): {valid: File[]; errors: string[]} {
+ const errors: string[] = [];
+ let valid = files;
+
+ if (accept) {
+ const acceptedTypes = accept.split(',').map(t => t.trim().toLowerCase());
+ valid = valid.filter(file => {
+ const matches = acceptedTypes.some(type => {
+ if (type.startsWith('.')) {
+ return file.name.toLowerCase().endsWith(type);
+ }
+ if (type.endsWith('/*')) {
+ return file.type.startsWith(type.slice(0, -1));
+ }
+ return file.type.toLowerCase() === type;
+ });
+ if (!matches) {
+ errors.push(`"${file.name}" is not an accepted file type`);
+ }
+ return matches;
+ });
+ }
+
+ if (maxSize != null) {
+ valid = valid.filter(file => {
+ if (file.size > maxSize) {
+ errors.push(`"${file.name}" exceeds ${formatFileSize(maxSize)} limit`);
+ return false;
+ }
+ return true;
+ });
+ }
+
+ if (isMultiple && maxFiles != null && valid.length > maxFiles) {
+ errors.push(`Maximum ${maxFiles} files allowed`);
+ valid = valid.slice(0, maxFiles);
+ }
+
+ return {valid, errors};
+}
+
+const styles = stylex.create({
+ dropzone: {
+ boxSizing: 'border-box',
+ position: 'relative',
+ zIndex: 1,
+ display: 'flex',
+ flexDirection: 'column',
+ alignItems: 'center',
+ justifyContent: 'center',
+ gap: spacingVars['--spacing-2'],
+ paddingBlock: spacingVars['--spacing-6'],
+ paddingInline: spacingVars['--spacing-4'],
+ borderWidth: borderVars['--border-width'],
+ borderStyle: 'dashed',
+ borderColor: {
+ default: colorVars['--color-border-emphasized'],
+ ':focus-within': colorVars['--color-accent'],
+ },
+ borderRadius: radiusVars['--radius-element'],
+ backgroundColor: colorVars['--color-background-surface'],
+ transitionProperty: 'border-color, box-shadow, background-color',
+ transitionDuration: {
+ default: durationVars['--duration-fast'],
+ '@media (prefers-reduced-motion: reduce)': '0s',
+ },
+ transitionTimingFunction: easeVars['--ease-standard'],
+ cursor: 'pointer',
+ outline: 'none',
+ },
+ dropzoneHover: {
+ boxShadow: {
+ default: null,
+ ':hover': {
+ '@media (hover: hover)': `inset 0 0 0 2px ${String(colorVars['--color-accent'])}33`,
+ },
+ },
+ },
+ dropzoneActive: {
+ borderColor: colorVars['--color-accent'],
+ backgroundColor: colorVars['--color-accent-muted'],
+ },
+ dropzoneDisabled: {
+ cursor: 'not-allowed',
+ opacity: 0.5,
+ borderColor: colorVars['--color-border-emphasized'],
+ },
+ compact: {
+ boxSizing: 'border-box',
+ position: 'relative',
+ zIndex: 1,
+ display: 'flex',
+ alignItems: 'center',
+ gap: spacingVars['--spacing-2'],
+ paddingBlock: spacingVars['--spacing-1'],
+ paddingInline: spacingVars['--spacing-2'],
+ borderWidth: borderVars['--border-width'],
+ borderStyle: 'solid',
+ borderColor: {
+ default: colorVars['--color-border-emphasized'],
+ ':focus-within': colorVars['--color-accent'],
+ },
+ borderRadius: radiusVars['--radius-element'],
+ backgroundColor: colorVars['--color-background-surface'],
+ transitionProperty: 'border-color, box-shadow',
+ transitionDuration: {
+ default: durationVars['--duration-fast'],
+ '@media (prefers-reduced-motion: reduce)': '0s',
+ },
+ transitionTimingFunction: easeVars['--ease-standard'],
+ boxShadow: {
+ default: 'none',
+ ':hover:not(:focus-within)': {
+ '@media (hover: hover)': `inset 0 0 0 2px ${String(colorVars['--color-accent'])}33`,
+ },
+ },
+ cursor: 'pointer',
+ height: sizeVars['--size-element-md'],
+ outline: 'none',
+ },
+ compactDisabled: {
+ cursor: 'not-allowed',
+ opacity: 0.5,
+ borderColor: colorVars['--color-border-emphasized'],
+ },
+ hiddenInput: {
+ position: 'absolute',
+ width: 1,
+ height: 1,
+ padding: 0,
+ margin: -1,
+ overflow: 'hidden',
+ clip: 'rect(0, 0, 0, 0)',
+ whiteSpace: 'nowrap',
+ borderWidth: 0,
+ },
+ placeholderText: {
+ fontFamily: typographyVars['--font-family-body'],
+ fontSize: {
+ default: typeScaleVars['--text-body-size'],
+ '@media (pointer: coarse)': `max(1rem, ${typeScaleVars['--text-body-size']})`,
+ },
+ lineHeight: typeScaleVars['--text-body-leading'],
+ color: colorVars['--color-text-secondary'],
+ textAlign: 'center',
+ userSelect: 'none',
+ },
+ fileNameText: {
+ fontFamily: typographyVars['--font-family-body'],
+ fontSize: {
+ default: typeScaleVars['--text-body-size'],
+ '@media (pointer: coarse)': `max(1rem, ${typeScaleVars['--text-body-size']})`,
+ },
+ lineHeight: typeScaleVars['--text-body-leading'],
+ color: colorVars['--color-text-primary'],
+ overflow: 'hidden',
+ textOverflow: 'ellipsis',
+ whiteSpace: 'nowrap',
+ flex: 1,
+ minWidth: 0,
+ },
+ clearButton: {
+ display: 'flex',
+ alignItems: 'center',
+ justifyContent: 'center',
+ padding: 0,
+ margin: 0,
+ borderWidth: 0,
+ borderStyle: 'none',
+ backgroundColor: 'transparent',
+ cursor: 'pointer',
+ borderRadius: radiusVars['--radius-element'],
+ outline: {
+ default: 'none',
+ ':focus-visible': `${borderVars['--border-width']} solid ${colorVars['--color-accent']}`,
+ },
+ outlineOffset: 1,
+ flexShrink: 0,
+ },
+ fileNameDropzone: {
+ textAlign: 'center',
+ whiteSpace: 'normal',
+ },
+ fileNameCompact: {
+ textAlign: 'start',
+ },
+ placeholderCompact: {
+ textAlign: 'start',
+ flex: 1,
+ minWidth: 0,
+ },
+ liveRegion: {
+ position: 'absolute',
+ width: 1,
+ height: 1,
+ padding: 0,
+ margin: -1,
+ overflow: 'hidden',
+ clip: 'rect(0, 0, 0, 0)',
+ whiteSpace: 'nowrap',
+ borderWidth: 0,
+ },
+});
+
+const statusBorderStyles = stylex.create({
+ warning: {
+ borderColor: colorVars['--color-warning'],
+ },
+ error: {
+ borderColor: colorVars['--color-error'],
+ },
+ success: {
+ borderColor: colorVars['--color-success'],
+ },
+});
+
+export interface XDSFileInputProps extends Omit<
+ XDSBaseProps,
+ 'onChange' | 'defaultValue' | 'value'
+> {
+ ref?: React.Ref<HTMLInputElement>;
+ /**
+ * Accessible label for the file input.
+ */
+ label: string;
+ /**
+ * Whether to visually hide the label (still accessible to screen readers).
+ * @default false
+ */
+ isLabelHidden?: boolean;
+ /**
+ * Currently selected file(s). Controlled component.
+ */
+ value: File | File[] | null;
+ /**
+ * Callback fired when files are selected or removed.
+ */
+ onChange: (files: File | File[] | null) => void;
+ /**
+ * Async change action (React 19 transitions pattern).
+ * Use for immediate upload on file selection.
+ */
+ onChangeAction?: (files: File | File[] | null) => Promise<void>;
+ /**
+ * Accepted file types. Uses the HTML accept attribute format.
+ * Examples: "image/*", ".pdf,.doc,.docx", "image/png,image/jpeg"
+ */
+ accept?: string;
+ /**
+ * Whether multiple files can be selected.
+ * When true, `value` and `onChange` use `File[]` instead of `File`.
+ * @default false
+ */
+ isMultiple?: boolean;
+ /**
+ * Maximum file size in bytes. Files exceeding this are rejected
+ * with an error status.
+ */
+ maxSize?: number;
+ /**
+ * Maximum number of files (only applies when `isMultiple` is true).
+ */
+ maxFiles?: number;
+ /**
+ * Whether the input is disabled.
+ * @default false
+ */
+ isDisabled?: boolean;
+ /**
+ * Whether the input is required.
+ * @default false
+ */
+ isRequired?: boolean;
+ /**
+ * Whether the input is in a loading state (e.g. uploading).
+ * @default false
+ */
+ isLoading?: boolean;
+ /**
+ * Validation status for the input.
+ */
+ status?: XDSInputStatus;
+ /**
+ * Description text displayed below the label.
+ */
+ description?: string;
+ /**
+ * Placeholder text shown when no file is selected.
+ * @default "Choose file" or "Choose files"
+ */
+ placeholder?: string;
+ /**
+ * Visual mode for the file input.
+ * - 'input': compact inline style, similar to a text input
+ * - 'dropzone': larger area with dashed border and drag-and-drop support
+ * @default 'input'
+ */
+ mode?: 'dropzone' | 'input';
+ /**
+ * Whether the field is optional. Mutually exclusive with isRequired.
+ * @default false
+ */
+ isOptional?: boolean;
+ /**
+ * Tooltip text to display in an info icon at the end of the label.
+ */
+ labelTooltip?: string;
+}
+
+/**
+ * A file input component with optional drag-and-drop support.
+ *
+ * @example
+ * ```
+ * <XDSFileInput label="Resume" value={file} onChange={setFile} accept=".pdf" />
+ * ```
+ */
+export function XDSFileInput({
+ label,
+ isLabelHidden = false,
+ value,
+ onChange,
+ onChangeAction,
+ accept,
+ isMultiple = false,
+ maxSize,
+ maxFiles,
+ isDisabled = false,
+ isRequired = false,
+ isLoading = false,
+ status: statusProp,
+ description,
+ placeholder,
+ mode = 'input',
+ isOptional = false,
+ labelTooltip,
+ xstyle,
+ className,
+ style,
+ ref,
+ ...rest
+}: XDSFileInputProps) {
+ const id = useId();
+ const descriptionID = useId();
+ const statusMessageID = useId();
+ const liveRegionID = useId();
+ const inputRef = useRef<HTMLInputElement | null>(null);
+ const [isDragOver, setIsDragOver] = useState(false);
+ const [validationError, setValidationError] = useState<string | null>(null);
+ const [, startTransition] = useTransition();
+
+ const status =
+ statusProp ??
+ (validationError
+ ? {type: 'error' as const, message: validationError}
+ : undefined);
+
+ const statusIconMap: Record<XDSInputStatusType, XDSIconName> = {
+ warning: 'warning',
+ error: 'error',
+ success: 'success',
+ };
+
+ const statusIconColorMap: Record<
+ XDSInputStatusType,
+ 'warning' | 'negative' | 'positive'
+ > = {
+ warning: 'warning',
+ error: 'negative',
+ success: 'positive',
+ };
+
+ const ariaDescribedBy =
+ [
+ description ? descriptionID : null,
+ status?.message ? statusMessageID : null,
+ ]
+ .filter(Boolean)
+ .join(' ') || undefined;
+
+ const defaultPlaceholder = isMultiple ? 'Choose files' : 'Choose file';
+ const displayPlaceholder = placeholder ?? defaultPlaceholder;
+
+ const handleFiles = useCallback(
+ (fileList: File[]) => {
+ if (isDisabled) return;
+
+ const {valid, errors} = validateFiles(
+ fileList,
+ accept,
+ maxSize,
+ maxFiles,
+ isMultiple,
+ );
+
+ if (errors.length > 0) {
+ setValidationError(errors[0]);
+ } else {
+ setValidationError(null);
+ }
+
+ if (valid.length === 0) {
+ onChange(null);
+ return;
+ }
+
+ const result = isMultiple ? valid : valid[0];
+ onChange(result);
+
+ if (onChangeAction) {
+ startTransition(async () => {
+ await onChangeAction(result);
+ });
+ }
+ },
+ [
+ accept,
+ isDisabled,
+ isMultiple,
+ maxFiles,
+ maxSize,
+ onChange,
+ onChangeAction,
+ startTransition,
+ ],
+ );
+
+ const handleInputChange = useCallback(
+ (e: React.ChangeEvent<HTMLInputElement>) => {
+ const fileList = Array.from(e.target.files ?? []);
+ handleFiles(fileList);
+ if (inputRef.current) {
+ inputRef.current.value = '';
+ }
+ },
+ [handleFiles],
+ );
+
+ const handleClear = useCallback(
+ (e: React.MouseEvent) => {
+ e.stopPropagation();
+ setValidationError(null);
+ onChange(null);
+ if (inputRef.current) {
+ inputRef.current.value = '';
+ inputRef.current.focus();
+ }
+ },
+ [onChange],
+ );
+
+ const handleClick = useCallback(() => {
+ if (!isDisabled) {
+ inputRef.current?.click();
+ }
+ }, [isDisabled]);
+
+ const handleKeyDown = useCallback(
+ (e: React.KeyboardEvent) => {
+ if ((e.key === 'Enter' || e.key === ' ') && !isDisabled) {
+ e.preventDefault();
+ inputRef.current?.click();
+ }
+ },
+ [isDisabled],
+ );
+
+ const handleDragEnter = useCallback(
+ (e: DragEvent) => {
+ e.preventDefault();
+ e.stopPropagation();
+ if (!isDisabled && mode === 'dropzone') {
+ setIsDragOver(true);
+ }
+ },
+ [isDisabled, mode],
+ );
+
+ const handleDragOver = useCallback(
+ (e: DragEvent) => {
+ e.preventDefault();
+ e.stopPropagation();
+ if (!isDisabled && mode === 'dropzone') {
+ setIsDragOver(true);
+ }
+ },
+ [isDisabled, mode],
+ );
+
+ const handleDragLeave = useCallback((e: DragEvent) => {
+ e.preventDefault();
+ e.stopPropagation();
+ setIsDragOver(false);
+ }, []);
+
+ const handleDrop = useCallback(
+ (e: DragEvent) => {
+ e.preventDefault();
+ e.stopPropagation();
+ setIsDragOver(false);
+ if (isDisabled || mode !== 'dropzone') return;
+ const fileList = Array.from(e.dataTransfer.files);
+ if (fileList.length > 0) {
+ handleFiles(fileList);
+ }
+ },
+ [isDisabled, mode, handleFiles],
+ );
+
+ const setRefs = useCallback(
+ (el: HTMLInputElement | null) => {
+ inputRef.current = el;
+ if (typeof ref === 'function') {
+ ref(el);
+ } else if (ref) {
+ (ref as React.MutableRefObject<HTMLInputElement | null>).current = el;
+ }
+ },
+ [ref],
+ );
+
+ const hasFiles =
+ value != null && (Array.isArray(value) ? value.length > 0 : true);
+ const fileNames = hasFiles
+ ? Array.isArray(value)
+ ? value.map(f => f.name).join(', ')
+ : value!.name
+ : null;
+
+ const renderDropzoneContent = () => {
+ if (isLoading) {
+ return <XDSSpinner size="md" />;
+ }
+ if (hasFiles) {
+ return (
+ <div {...stylex.props(styles.fileNameText, styles.fileNameDropzone)}>
+ {fileNames}
+ </div>
+ );
+ }
+ return (
+ <>
+ <XDSIcon icon="arrowUp" size="md" color="secondary" />
+ <span {...stylex.props(styles.placeholderText)}>
+ {isDragOver ? 'Drop files here' : displayPlaceholder}
+ </span>
+ </>
+ );
+ };
+
+ const renderCompactContent = () => {
+ if (isLoading) {
+ return (
+ <>
+ <span {...stylex.props(styles.fileNameText)}>
+ {fileNames ?? displayPlaceholder}
+ </span>
+ <XDSSpinner size="sm" />
+ </>
+ );
+ }
+ return (
+ <>
+ <XDSIcon icon="arrowUp" size="sm" color="secondary" />
+ <span
+ {...stylex.props(
+ hasFiles ? styles.fileNameText : styles.placeholderText,
+ hasFiles ? styles.fileNameCompact : styles.placeholderCompact,
+ )}>
+ {fileNames ?? displayPlaceholder}
+ </span>
+ {status && (
+ <XDSIcon
+ icon={statusIconMap[status.type]}
+ size="md"
+ color={statusIconColorMap[status.type]}
+ />
+ )}
+ </>
+ );
+ };
+
+ const isDropzone = mode === 'dropzone';
+
+ const dragDropProps = isDropzone
+ ? {
+ onDragEnter: handleDragEnter,
+ onDragOver: handleDragOver,
+ onDragLeave: handleDragLeave,
+ onDrop: handleDrop,
+ }
+ : {};
+
+ return (
+ <XDSField
+ label={label}
+ isLabelHidden={isLabelHidden}
+ description={description}
+ inputID={id}
+ descriptionID={description ? descriptionID : undefined}
+ isOptional={isOptional}
+ isRequired={isRequired}
+ isDisabled={isDisabled}
+ status={
+ status
+ ? {
+ type: status.type,
+ message: status.message,
+ messageID: status.message ? statusMessageID : undefined,
+ }
+ : undefined
+ }
+ labelTooltip={labelTooltip}>
+ <div
+ role="button"
+ tabIndex={isDisabled ? -1 : 0}
+ onClick={handleClick}
+ onKeyDown={handleKeyDown}
+ aria-label={label}
+ aria-busy={isLoading || undefined}
+ {...dragDropProps}
+ {...mergeProps(
+ xdsClassName('file-input', {mode, status: status?.type ?? null}),
+ stylex.props(
+ isDropzone ? styles.dropzone : styles.compact,
+ isDropzone && !isDisabled && styles.dropzoneHover,
+ isDropzone && isDragOver && styles.dropzoneActive,
+ isDropzone && isDisabled && styles.dropzoneDisabled,
+ !isDropzone && isDisabled && styles.compactDisabled,
+ status && statusBorderStyles[status.type],
+ xstyle,
+ ),
+ className,
+ style,
+ )}>
+ <input
+ {...rest}
+ ref={setRefs}
+ id={id}
+ type="file"
+ accept={accept}
+ multiple={isMultiple}
+ disabled={isDisabled}
+ onChange={handleInputChange}
+ aria-describedby={ariaDescribedBy}
+ aria-required={isRequired ? 'true' : undefined}
+ aria-invalid={status?.type === 'error' ? 'true' : undefined}
+ tabIndex={-1}
+ {...stylex.props(styles.hiddenInput)}
+ />
+ {isDropzone ? renderDropzoneContent() : renderCompactContent()}
+ {hasFiles && !isDisabled && !isLoading && (
+ <button
+ type="button"
+ onClick={handleClear}
+ aria-label={`Clear ${label}`}
+ {...stylex.props(styles.clearButton)}>
+ <XDSIcon icon="close" size="sm" color="secondary" />
+ </button>
+ )}
+ </div>
+ <div
+ id={liveRegionID}
+ role="status"
+ aria-live="polite"
+ {...stylex.props(styles.liveRegion)}>
+ {validationError}
+ </div>
+ </XDSField>
+ );
+}
+
+XDSFileInput.displayName = 'XDSFileInput';
diff --git a/packages/core/src/FileInput/index.ts b/packages/core/src/FileInput/index.ts
new file mode 100644
index 0000000000..6076c81521
--- /dev/null
+++ b/packages/core/src/FileInput/index.ts
@@ -0,0 +1,19 @@
+// Copyright (c) Meta Platforms, Inc. and affiliates.
+
+'use client';
+
+/**
+ * @file index.ts
+ * @input Imports XDSFileInput component and types from XDSFileInput.tsx
+ * @output Exports XDSFileInput, XDSFileInputProps, XDSFileInputStatus, XDSFileInputStatusType
+ * @position Component entry point; re-exported by /packages/core/src/index.ts
+ *
+ * SYNC: When modified, update this header and /packages/core/src/FileInput/FileInput.doc.mjs
+ */
+
+export {XDSFileInput} from './XDSFileInput';
+export type {
+ XDSFileInputProps,
+ XDSFileInputStatus,
+ XDSFileInputStatusType,
+} from './XDSFileInput';
diff --git a/packages/core/src/index.ts b/packages/core/src/index.ts
index ca156a1cc5..e0a497f3a5 100644
--- a/packages/core/src/index.ts
+++ b/packages/core/src/index.ts
@@ -54,6 +54,7 @@ export * from './DateInput';
export * from './DateTimePicker';
export * from './DateRangePicker';
export * from './Field';
+export * from './FileInput';
export * from './FormLayout';
export * from './Grid';
export * from './Section';