import React, { useRef, useState } from "react" import uuid from "uuid" import { FileValue } from "@mwater/expressions" import { FileManager } from "./formContext" import FileLinkComponent from "./FileLinkComponent" import { formatFileSize } from "./utils" export interface FileEditorComponentProps { fileManager: FileManager file?: FileValue | null /** Called when file changed */ onFileChange?: (file: FileValue | null) => void /** HTML accept attribute for file input (e.g. ".pdf,image/*") */ accept?: string /** Maximum file size in bytes */ maxFileSize?: number } /** Editor for a single file (FileValue). Handles picking, uploading, display and removal. */ export default function FileEditorComponent(props: FileEditorComponentProps) { const { fileManager, file, onFileChange, accept, maxFileSize } = props const [uploading, setUploading] = useState(false) const [error, setError] = useState(null) const inputRef = useRef(null) const handleFileSelect = async (ev: React.ChangeEvent) => { const selected = ev.target.files?.[0] if (!selected || !onFileChange) return if (maxFileSize && selected.size > maxFileSize) { setError(T("File exceeds maximum size of {0} MB", (maxFileSize / (1024 * 1024)).toFixed(0))) return } const fileId = uuid().replace(/-/g, "") setUploading(true) setError(null) try { await fileManager.uploadFile(selected, fileId) onFileChange({ id: fileId, filename: selected.name, size: selected.size, mimetype: selected.type || "application/octet-stream" }) } catch (err: any) { setError(err.message || T("Upload failed")) } finally { setUploading(false) if (inputRef.current) { inputRef.current.value = "" } } } const handleRemove = () => { if (onFileChange) { onFileChange(null) } } if (file) { const isVideo = file.mimetype?.startsWith("video/") return (
{isVideo ? file.filename : {file.filename}} ({formatFileSize(file.size)}) {onFileChange && ( )}
{isVideo && (
{file.filename}
)}
) } return (
{uploading ? ( {T("Uploading...")} ) : (
)} {error &&
{error}
}
) }