fix: make the file sync work on onboarding

This commit is contained in:
Nathnael
2026-06-26 12:31:08 +00:00
parent f86bdb1c36
commit 552e6bcd16
3 changed files with 501 additions and 308 deletions

View File

@@ -1,8 +1,5 @@
import React, { useState, useMemo, useRef } from "react";
import {
IFileUploadSetting,
IFileUploadField,
} from "@edr/types/freight";
import { IFileUploadSetting, IFileUploadField } from "@edr/types/freight";
import {
UploadCloud,
FileText,
@@ -24,12 +21,20 @@ export interface SmartFileInputProps {
onChange?: (value: Record<string, File | File[] | null>) => void;
/** External form errors mapped by fileKey. */
errors?: Record<string, string>;
/**
* fileKeys whose document is already uploaded on the server. Such fields show
* an "Already uploaded" badge and a replace-oriented dropzone hint, even when
* no in-memory File is currently selected for them.
*/
uploadedKeys?: string[];
/** Disabled state for the entire file input group. */
disabled?: boolean;
/** Display variant style. Default is "default" (large dropzone). Minimal renders a compact upload button. */
variant?: "default" | "minimal";
/** Optional custom container CSS classes. */
className?: string;
containerClassName?: string;
}
/** Helper to format file sizes in bytes to a human-readable string. */
@@ -45,23 +50,23 @@ function formatBytes(bytes: number, decimals = 2) {
/** Render a suitable icon based on file extension. */
function FileIcon({ name, className }: { name: string; className?: string }) {
const ext = name.split(".").pop()?.toLowerCase() || "";
if (ext === "pdf") {
return <FileText className={cn("text-red-500", className)} />;
}
if (["png", "jpg", "jpeg", "webp", "svg", "gif"].includes(ext)) {
return <ImageIcon className={cn("text-blue-500", className)} />;
}
if (["csv", "xls", "xlsx"].includes(ext)) {
return <FileText className={cn("text-emerald-500", className)} />;
}
if (["zip", "rar", "tar", "gz", "7z"].includes(ext)) {
return <File className={cn("text-amber-500", className)} />;
}
return <File className={cn("text-slate-400", className)} />;
}
@@ -70,16 +75,20 @@ export function SmartFileInput({
value,
onChange,
errors,
uploadedKeys,
disabled = false,
variant = "default",
className,
containerClassName,
}: SmartFileInputProps) {
// Local state to manage files when the component is used in an uncontrolled manner
const [internalFiles, setInternalFiles] = useState<Record<string, File[]>>({});
const [internalFiles, setInternalFiles] = useState<Record<string, File[]>>(
{},
);
// Local validation errors
const [localErrors, setLocalErrors] = useState<Record<string, string>>({});
// Drag-and-drop state active per field
const [dragActive, setDragActive] = useState<Record<string, boolean>>({});
@@ -93,10 +102,13 @@ export function SmartFileInput({
// Create a map of fields for quick lookup
const fieldsMap = useMemo(() => {
return file.fields.reduce((acc, currentField) => {
acc[currentField.fileKey] = currentField;
return acc;
}, {} as Record<string, IFileUploadField>);
return file.fields.reduce(
(acc, currentField) => {
acc[currentField.fileKey] = currentField;
return acc;
},
{} as Record<string, IFileUploadField>,
);
}, [file.fields]);
// Resolve current files list for a field
@@ -109,8 +121,8 @@ export function SmartFileInput({
const handleFilesChange = (fieldKey: string, newFiles: File[]) => {
const field = fieldsMap[fieldKey];
if (!field) return;
const newValue = field.isMultiple ? newFiles : (newFiles[0] || null);
const newValue = field.isMultiple ? newFiles : newFiles[0] || null;
if (onChange) {
const updatedValues = {
@@ -129,10 +141,10 @@ export function SmartFileInput({
const processFiles = (field: IFileUploadField, incomingFiles: File[]) => {
const currentFiles = getFilesForField(field.fileKey);
const maxAllowed = field.isMultiple ? Math.max(1, field.maxFiles) : 1;
// Clean up extensions (e.g. '.pdf' or 'pdf' -> 'pdf')
const allowedExts = field.allowedExtensions.map((ext) =>
ext.toLowerCase().replace(/^\./, "")
ext.toLowerCase().replace(/^\./, ""),
);
let validIncoming: File[] = [];
@@ -140,13 +152,12 @@ export function SmartFileInput({
for (const fileObj of incomingFiles) {
const ext = fileObj.name.split(".").pop()?.toLowerCase() || "";
const isExtValid =
allowedExts.length === 0 || allowedExts.includes(ext);
const isExtValid = allowedExts.length === 0 || allowedExts.includes(ext);
const isSizeValid = fileObj.size <= field.maxSizeMb * 1024 * 1024;
if (!isExtValid) {
errorMsg = `Invalid file extension. Allowed: ${field.allowedExtensions.join(
", "
", ",
)}`;
break;
}
@@ -187,7 +198,11 @@ export function SmartFileInput({
handleFilesChange(field.fileKey, newFilesList);
};
const handleDrag = (e: React.DragEvent, fieldKey: string, active: boolean) => {
const handleDrag = (
e: React.DragEvent,
fieldKey: string,
active: boolean,
) => {
e.preventDefault();
e.stopPropagation();
if (disabled) return;
@@ -208,7 +223,7 @@ export function SmartFileInput({
const handleFileSelect = (
e: React.ChangeEvent<HTMLInputElement>,
field: IFileUploadField
field: IFileUploadField,
) => {
if (e.target.files && e.target.files.length > 0) {
const filesArray = Array.from(e.target.files);
@@ -246,179 +261,275 @@ export function SmartFileInput({
{file.description}
</div>
)}
{sortedFields.map((field) => {
const currentFiles = getFilesForField(field.fileKey);
const maxFiles = field.isMultiple ? Math.max(1, field.maxFiles) : 1;
const reachedLimit = currentFiles.length >= maxFiles;
const fieldError = errors?.[field.fileKey] || localErrors[field.fileKey];
const isDragOver = dragActive[field.fileKey];
// Format accepted files for the HTML input element
const acceptString = field.allowedExtensions
.map((ext) => (ext.startsWith(".") ? ext : `.${ext}`))
.join(",");
<div className={cn("flex flex-col gap-6", containerClassName)}>
{sortedFields.map((field) => {
const currentFiles = getFilesForField(field.fileKey);
const maxFiles = field.isMultiple ? Math.max(1, field.maxFiles) : 1;
const reachedLimit = currentFiles.length >= maxFiles;
const fieldError =
errors?.[field.fileKey] || localErrors[field.fileKey];
const isDragOver = dragActive[field.fileKey];
// Already uploaded server-side and nothing newly picked to replace it.
const isUploaded =
(uploadedKeys?.includes(field.fileKey) ?? false) &&
currentFiles.length === 0;
return (
<div key={field.id || field.fileKey} className="flex flex-col gap-2">
{/* Field Header */}
<div className="flex flex-col md:flex-row md:items-baseline justify-between gap-1">
<label className="text-sm font-semibold text-foreground flex items-center gap-1">
{field.fileLabel}
{field.isRequired && (
<span className="text-destructive font-bold" aria-hidden="true">
*
</span>
)}
</label>
<span className="text-xs text-muted-foreground">
Max size: {field.maxSizeMb}MB
{field.isMultiple && ` • Files: ${currentFiles.length}/${maxFiles}`}
</span>
</div>
// Format accepted files for the HTML input element
const acceptString = field.allowedExtensions
.map((ext) => (ext.startsWith(".") ? ext : `.${ext}`))
.join(",");
{/* Help / Description Text */}
{field.helpText && (
<p className="text-xs text-muted-foreground">{field.helpText}</p>
)}
{/* Selected Files List */}
{currentFiles.length > 0 && (
<div className="flex flex-col gap-2">
{currentFiles.map((fileObj, idx) => (
<div
key={`${fileObj.name}-${idx}`}
className={cn(
"flex items-center justify-between p-3 rounded-lg border bg-card transition shadow-2xs hover:shadow-xs",
fieldError ? "border-destructive/30" : "border-border"
return (
<div
key={field.id || field.fileKey}
className="flex flex-col gap-2"
>
{/* Field Header */}
<div className="flex flex-col md:flex-row md:items-baseline justify-between gap-1">
<label className="text-sm font-semibold text-foreground flex items-center gap-1.5">
<span className="flex items-center gap-1">
{field.fileLabel}
{field.isRequired && (
<span
className="text-destructive font-bold"
aria-hidden="true"
>
*
</span>
)}
>
<div className="flex items-center gap-3 min-w-0">
<div className="p-2 bg-muted rounded-md flex items-center justify-center">
<FileIcon name={fileObj.name} className="h-5 w-5" />
</div>
<div className="min-w-0">
<p className="text-sm font-medium text-foreground truncate max-w-[200px] md:max-w-md" title={fileObj.name}>
{fileObj.name}
</p>
<div className="flex items-center gap-2 mt-0.5">
<span className="text-xs text-muted-foreground">
{formatBytes(fileObj.size)}
</span>
<span className="flex items-center gap-0.5 text-xs text-primary font-medium">
<CheckCircle2 className="h-3 w-3" /> Ready
</span>
</span>
{isUploaded && (
<span className="inline-flex items-center gap-1 rounded-full bg-emerald-50 px-2 py-0.5 text-[11px] font-medium text-emerald-600 dark:bg-emerald-500/10 dark:text-emerald-400">
<CheckCircle2 className="h-3 w-3" /> Already uploaded
</span>
)}
</label>
<span className="text-xs text-muted-foreground">
Max size: {field.maxSizeMb}MB
{field.isMultiple &&
` • Files: ${currentFiles.length}/${maxFiles}`}
</span>
</div>
{/* Help / Description Text */}
{field.helpText && (
<p className="text-xs text-muted-foreground">
{field.helpText}
</p>
)}
{/* Selected Files List */}
{currentFiles.length > 0 && (
<div className="flex flex-col gap-2">
{currentFiles.map((fileObj, idx) => (
<div
key={`${fileObj.name}-${idx}`}
className={cn(
"flex items-center justify-between p-3 rounded-lg border bg-card transition shadow-2xs hover:shadow-xs",
fieldError ? "border-destructive/30" : "border-border",
)}
>
<div className="flex items-center gap-3 min-w-0">
<div className="p-2 bg-muted rounded-md flex items-center justify-center">
<FileIcon name={fileObj.name} className="h-5 w-5" />
</div>
<div className="min-w-0">
<p
className="text-sm font-medium text-foreground truncate max-w-[200px] md:max-w-md"
title={fileObj.name}
>
{fileObj.name}
</p>
<div className="flex items-center gap-2 mt-0.5">
<span className="text-xs text-muted-foreground">
{formatBytes(fileObj.size)}
</span>
<span className="flex items-center gap-0.5 text-xs text-primary font-medium">
<CheckCircle2 className="h-3 w-3" /> Ready
</span>
</div>
</div>
</div>
<button
type="button"
disabled={disabled}
onClick={() => removeFile(field.fileKey, idx)}
className={cn(
"p-1.5 rounded-md text-muted-foreground hover:text-destructive hover:bg-destructive/10 transition-colors",
disabled && "opacity-50 pointer-events-none",
)}
aria-label={`Remove file ${fileObj.name}`}
>
<Trash2 className="h-4 w-4" />
</button>
{/* Hidden inputs to represent file details in traditional form submissions */}
<input
type="hidden"
name={
field.isMultiple
? `${field.fileKey}[]`
: field.fileKey
}
value={fileObj.name}
/>
</div>
))}
</div>
)}
{/* Dropzone area */}
{!reachedLimit &&
(variant === "minimal" ? (
<div className="flex flex-wrap items-center gap-3">
<Button
type="button"
variant="outline"
size="sm"
disabled={disabled}
onClick={() =>
fileInputRefs.current[field.fileKey]?.click()
}
className="gap-1.5 cursor-pointer"
>
<UploadCloud className="h-4 w-4 text-muted-foreground" />
<span>{isUploaded ? "Replace File" : "Upload File"}</span>
</Button>
<input
type="file"
ref={(el) => {
if (fileInputRefs.current) {
fileInputRefs.current[field.fileKey] = el;
}
}}
multiple={field.isMultiple}
accept={acceptString}
disabled={disabled}
onChange={(e) => handleFileSelect(e, field)}
className="hidden"
/>
<span className="text-xs text-muted-foreground">
Accepts:{" "}
{field.allowedExtensions.join(", ").toUpperCase() ||
"All"}
</span>
</div>
) : isUploaded ? (
// Uploaded state: a solid success panel that still doubles as a
// replace target (click anywhere or drag a new file onto it).
<div
onDragOver={(e) => handleDrag(e, field.fileKey, true)}
onDragLeave={(e) => handleDrag(e, field.fileKey, false)}
onDrop={(e) => handleDrop(e, field)}
className={cn(
"group relative flex items-center gap-4 rounded-lg border p-4 transition-all",
isDragOver
? "border-2 border-dashed border-primary bg-primary/5 dark:bg-primary/10"
: "border-emerald-300/70 bg-emerald-50/60 dark:border-emerald-500/30 dark:bg-emerald-500/10",
disabled &&
"opacity-50 pointer-events-none cursor-not-allowed",
)}
>
<input
type="file"
multiple={field.isMultiple}
accept={acceptString}
disabled={disabled}
onChange={(e) => handleFileSelect(e, field)}
id={`file-input-${field.fileKey}`}
className="absolute inset-0 w-full h-full opacity-0 cursor-pointer disabled:cursor-not-allowed"
aria-label={`Replace ${field.fileLabel}`}
/>
<div className="flex h-10 w-10 shrink-0 items-center justify-center rounded-full bg-emerald-100 text-emerald-600 dark:bg-emerald-500/20 dark:text-emerald-400">
{isDragOver ? (
<UploadCloud className="h-5 w-5 animate-bounce" />
) : (
<CheckCircle2 className="h-5 w-5" />
)}
</div>
<button
type="button"
disabled={disabled}
onClick={() => removeFile(field.fileKey, idx)}
className={cn(
"p-1.5 rounded-md text-muted-foreground hover:text-destructive hover:bg-destructive/10 transition-colors",
disabled && "opacity-50 pointer-events-none"
)}
aria-label={`Remove file ${fileObj.name}`}
>
<Trash2 className="h-4 w-4" />
</button>
{/* Hidden inputs to represent file details in traditional form submissions */}
<div className="min-w-0 flex-1">
<p className="text-sm font-semibold text-foreground">
{isDragOver ? "Drop to replace" : "Document uploaded"}
</p>
<p className="mt-0.5 text-xs text-muted-foreground">
{isDragOver
? "Release to replace the document on file."
: "Saved to your application. Drag a new file here or click to replace it."}
</p>
</div>
<span className="hidden shrink-0 items-center gap-1.5 rounded-md border border-border bg-card px-3 py-1.5 text-xs font-medium text-foreground shadow-2xs transition group-hover:border-primary/50 group-hover:text-primary sm:inline-flex">
<UploadCloud className="h-3.5 w-3.5" />
Replace
</span>
</div>
) : (
<div
onDragOver={(e) => handleDrag(e, field.fileKey, true)}
onDragLeave={(e) => handleDrag(e, field.fileKey, false)}
onDrop={(e) => handleDrop(e, field)}
className={cn(
"relative border-2 border-dashed rounded-lg p-6 flex flex-col items-center justify-center text-center transition-all bg-card/50",
isDragOver
? "border-primary bg-primary/5 dark:bg-primary/10"
: "border-border hover:border-primary/50 hover:bg-muted/10",
fieldError &&
"border-destructive hover:border-destructive/80",
disabled &&
"opacity-50 pointer-events-none cursor-not-allowed",
)}
>
<input
type="hidden"
name={field.isMultiple ? `${field.fileKey}[]` : field.fileKey}
value={fileObj.name}
type="file"
multiple={field.isMultiple}
accept={acceptString}
disabled={disabled}
onChange={(e) => handleFileSelect(e, field)}
id={`file-input-${field.fileKey}`}
className="absolute inset-0 w-full h-full opacity-0 cursor-pointer disabled:cursor-not-allowed"
/>
<div className="p-3 bg-muted rounded-full mb-3 text-muted-foreground transition group-hover:scale-110">
<UploadCloud
className={cn(
"h-6 w-6 text-muted-foreground",
isDragOver && "text-primary animate-bounce",
)}
/>
</div>
<p className="text-sm font-semibold text-foreground">
Drag & drop your file here, or{" "}
<span className="text-primary font-bold hover:underline">
browse
</span>
</p>
<p className="text-xs text-muted-foreground mt-1">
Supported formats:{" "}
{field.allowedExtensions.join(", ").toUpperCase() ||
"All"}
</p>
</div>
))}
</div>
)}
{/* Dropzone area */}
{!reachedLimit && (
variant === "minimal" ? (
<div className="flex flex-wrap items-center gap-3">
<Button
type="button"
variant="outline"
size="sm"
disabled={disabled}
onClick={() => fileInputRefs.current[field.fileKey]?.click()}
className="gap-1.5 cursor-pointer"
>
<UploadCloud className="h-4 w-4 text-muted-foreground" />
<span>Upload File</span>
</Button>
<input
type="file"
ref={(el) => {
if (fileInputRefs.current) {
fileInputRefs.current[field.fileKey] = el;
}
}}
multiple={field.isMultiple}
accept={acceptString}
disabled={disabled}
onChange={(e) => handleFileSelect(e, field)}
className="hidden"
/>
<span className="text-xs text-muted-foreground">
Accepts: {field.allowedExtensions.join(", ").toUpperCase() || "All"}
</span>
{/* Validation Error Message */}
{fieldError && (
<div className="flex items-center gap-1.5 mt-1 text-xs text-destructive animate-in fade-in slide-in-from-top-1 duration-200">
<AlertCircle className="h-3.5 w-3.5" />
<span>{fieldError}</span>
</div>
) : (
<div
onDragOver={(e) => handleDrag(e, field.fileKey, true)}
onDragLeave={(e) => handleDrag(e, field.fileKey, false)}
onDrop={(e) => handleDrop(e, field)}
className={cn(
"relative border-2 border-dashed rounded-lg p-6 flex flex-col items-center justify-center text-center transition-all bg-card/50",
isDragOver
? "border-primary bg-primary/5 dark:bg-primary/10"
: "border-border hover:border-primary/50 hover:bg-muted/10",
fieldError && "border-destructive hover:border-destructive/80",
disabled && "opacity-50 pointer-events-none cursor-not-allowed"
)}
>
<input
type="file"
multiple={field.isMultiple}
accept={acceptString}
disabled={disabled}
onChange={(e) => handleFileSelect(e, field)}
id={`file-input-${field.fileKey}`}
className="absolute inset-0 w-full h-full opacity-0 cursor-pointer disabled:cursor-not-allowed"
/>
<div className="p-3 bg-muted rounded-full mb-3 text-muted-foreground transition group-hover:scale-110">
<UploadCloud className={cn("h-6 w-6 text-muted-foreground", isDragOver && "text-primary animate-bounce")} />
</div>
<p className="text-sm font-semibold text-foreground">
Drag & drop your file here, or <span className="text-primary font-bold hover:underline">browse</span>
</p>
<p className="text-xs text-muted-foreground mt-1">
Supported formats: {field.allowedExtensions.join(", ").toUpperCase() || "All"}
</p>
</div>
)
)}
{/* Validation Error Message */}
{fieldError && (
<div className="flex items-center gap-1.5 mt-1 text-xs text-destructive animate-in fade-in slide-in-from-top-1 duration-200">
<AlertCircle className="h-3.5 w-3.5" />
<span>{fieldError}</span>
</div>
)}
</div>
);
})}
)}
</div>
);
})}
</div>
</div>
);
}