import React, { useCallback, useImperativeHandle, useRef } from 'react'; import { AttachmentChip } from './attachment-chip'; import { fileToAttachmentValue } from './file-utils'; import styles from './silke-command-text-field.module.scss'; import { SilkeFileValue, SilkeImageValue } from './utils'; interface AttachmentListProps { acceptedTypes: string[]; attachments: (SilkeImageValue | SilkeFileValue)[]; disabled?: boolean; onAdd: (attachments: (SilkeImageValue | SilkeFileValue)[]) => void; onRemove: (index: number) => void; } export interface AttachmentListHandle { /** Open the file picker dialog */ openFilePicker: () => void; } export const AttachmentList = React.forwardRef( ({ acceptedTypes, attachments, disabled, onAdd, onRemove }, ref) => { const fileInputRef = useRef(null); const handleFileSelect = useCallback( (e: React.ChangeEvent) => { const { files } = e.target; if (!files || files.length === 0) return; Promise.all( Array.from(files).map((file) => fileToAttachmentValue(file, acceptedTypes)), ).then((results) => { const valid = results.filter((v): v is SilkeImageValue | SilkeFileValue => v !== null); if (valid.length > 0) onAdd(valid); }); // Reset so the same file can be selected again e.target.value = ''; }, [acceptedTypes, onAdd], ); useImperativeHandle(ref, () => ({ openFilePicker: () => fileInputRef.current?.click(), })); return ( <> {attachments.length > 0 && (
{attachments.map((attachment, idx) => ( onRemove(idx)} /> ))}
)} ); }, ); AttachmentList.displayName = 'AttachmentList';