Skip to content
Merged
Show file tree
Hide file tree
Changes from 1 commit
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
42 changes: 37 additions & 5 deletions packages/utah-design-system/src/components/FileInput.stories.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -93,7 +93,7 @@ export const ReactHookFormValidation: Story = {
// eslint-disable-next-line react-hooks/rules-of-hooks
const { control, handleSubmit } = useForm({
defaultValues: {
files: null,
files: null as File[] | null,
},
});

Expand All @@ -108,13 +108,12 @@ export const ReactHookFormValidation: Story = {
control={control}
name="files"
rules={{ required: 'Please select at least one file' }}
render={({ field: { onChange, ...field }, fieldState }) => (
render={({ field: { onChange, value, ...field }, fieldState }) => (
<FileInput
errorMessage={fieldState.error?.message}
isInvalid={fieldState.invalid}
onSelect={(fileList) => {
onChange(fileList);
}}
value={value}
onChange={onChange}
{...field}
{...args}
/>
Expand Down Expand Up @@ -167,3 +166,36 @@ export const HtmlValidation: Story = {
isRequired: true,
},
};

export const Controlled: Story = {
render: (args) => {
// eslint-disable-next-line react-hooks/rules-of-hooks
const [files, setFiles] = useState<File[] | null>(null);

return (
<div className="flex flex-col items-start gap-4">
<FileInput {...args} value={files} onChange={setFiles} />
<div className="flex gap-2">
<Button
onPress={() => setFiles(null)}
variant="secondary"
isDisabled={!files || files.length === 0}
>
Reset
</Button>
</div>
{files && files.length > 0 && (
<div className="text-sm text-zinc-600 dark:text-zinc-400">
Parent state: {files.map((f) => f.name).join(', ')}
</div>
)}
</div>
);
},
args: {
label: 'Upload document (controlled)',
placeholder: 'Drag a file here or click to upload',
description:
'This input is controlled. Click Reset to clear files from parent state.',
},
};
65 changes: 31 additions & 34 deletions packages/utah-design-system/src/components/FileInput.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -18,7 +18,8 @@ import { Description, Label } from './Field';
import { Tooltip } from './Tooltip';
import { focusRing } from './utils';

export interface FileInputProps extends Omit<AriaFileTriggerProps, 'children'> {
export interface FileInputProps
extends Omit<AriaFileTriggerProps, 'children' | 'onSelect'> {
label?: string;
description?: string;
errorMessage?: string | ((validation: ValidationResult) => string);
Expand All @@ -37,6 +38,16 @@ export interface FileInputProps extends Omit<AriaFileTriggerProps, 'children'> {
* Custom class for the drop zone container
*/
className?: string;
/**
* Controlled value - the current files selected.
* When provided, the component becomes controlled.
*/
value?: File[] | null;
/**
* Callback when files change.
* We use onChange rather than onSelect to make it clear that we are diverting from AriaFileTrigger which doesn't support being controlled
*/
onChange?: (files: File[] | null) => void;
}

const labelStyles = tv({
Expand Down Expand Up @@ -143,16 +154,28 @@ export function FileInput({
className,
allowsMultiple,
acceptedFileTypes,
onSelect,
value,
onChange,
...props
}: FileInputProps) {
const [selectedFiles, setSelectedFiles] = useState<File[]>([]);
const isControlled = value !== undefined;

const [internalFiles, setInternalFiles] = useState<File[]>([]);

// Use controlled value if provided, otherwise use internal state
const selectedFiles = isControlled ? (value ?? []) : internalFiles;

const updateFiles = (files: File[] | null) => {
if (!isControlled) {
setInternalFiles(files ?? []);
}
onChange?.(files);
};

const handleSelect = (fileList: FileList | null) => {
if (fileList) {
const files = Array.from(fileList);
setSelectedFiles(files);
onSelect?.(fileList);
updateFiles(files);
}
};

Expand All @@ -176,44 +199,18 @@ export function FileInput({
: filesToAdd;

if (filteredFiles.length > 0) {
setSelectedFiles(filteredFiles);

// Create FileList from files
try {
const dataTransfer = new DataTransfer();
filteredFiles.forEach((file) => dataTransfer.items.add(file));
onSelect?.(dataTransfer.files);
} catch (error) {
console.warn('DataTransfer API not available:', error);
}
updateFiles(filteredFiles);
}
}
};

const removeFile = (index: number) => {
const updated = selectedFiles.filter((_, i) => i !== index);
setSelectedFiles(updated);

if (updated.length === 0) {
onSelect?.(null);
return;
}

// Create a new FileList-like object and notify parent
try {
const dataTransfer = new DataTransfer();
updated.forEach((file) => dataTransfer.items.add(file));
onSelect?.(dataTransfer.files);
} catch (error) {
// DataTransfer not available in this environment
console.warn('DataTransfer API not available:', error);
}
updateFiles(updated.length === 0 ? null : updated);
};

const clearFiles = () => {
setSelectedFiles([]);
// Notify parent that files have been cleared
onSelect?.(null);
updateFiles(null);
};

return (
Expand Down