mirror of
https://github.com/Tria-plc/edr-platform.git
synced 2026-09-07 13:05:44 +00:00
Merge pull request #15 from Tria-plc/forms
feat: build a global smart file input field
This commit is contained in:
191
apps/edr-freight-web/portal/src/services/api.ts
Normal file
191
apps/edr-freight-web/portal/src/services/api.ts
Normal file
@@ -0,0 +1,191 @@
|
|||||||
|
import type { Freight, PaginatedResponse } from "@edr/types";
|
||||||
|
import { client, endpoint, unwrap } from "@/utils/api";
|
||||||
|
import type {
|
||||||
|
CreateFileUploadFieldDto,
|
||||||
|
CreateFileUploadSettingDto,
|
||||||
|
FileUploadField,
|
||||||
|
FileUploadSetting,
|
||||||
|
UpdateFileUploadFieldDto,
|
||||||
|
UpdateFileUploadSettingDto,
|
||||||
|
} from "@/types/fileUploadSettings";
|
||||||
|
|
||||||
|
// ---------------------------------------------------------------------------
|
||||||
|
// API definition
|
||||||
|
// ---------------------------------------------------------------------------
|
||||||
|
|
||||||
|
export const api = {
|
||||||
|
bookings: {
|
||||||
|
list: endpoint<void, PaginatedResponse<Freight.IBooking>>(
|
||||||
|
"bookings",
|
||||||
|
"list",
|
||||||
|
async () => {
|
||||||
|
const { data } = await client.get("/bookings");
|
||||||
|
return unwrap(data);
|
||||||
|
},
|
||||||
|
),
|
||||||
|
|
||||||
|
get: endpoint<{ id: string }, Freight.IBooking>(
|
||||||
|
"bookings",
|
||||||
|
"get",
|
||||||
|
async ({ id }) => {
|
||||||
|
const { data } = await client.get(`/bookings/${id}`);
|
||||||
|
return unwrap(data);
|
||||||
|
},
|
||||||
|
),
|
||||||
|
|
||||||
|
create: endpoint<
|
||||||
|
{
|
||||||
|
reference: string;
|
||||||
|
customerId: string;
|
||||||
|
scheduledDate: string;
|
||||||
|
totalAmount: number;
|
||||||
|
trainId?: string;
|
||||||
|
},
|
||||||
|
Freight.IBooking
|
||||||
|
>("bookings", "create", async (input) => {
|
||||||
|
const { data } = await client.post("/bookings", input);
|
||||||
|
return unwrap(data);
|
||||||
|
}),
|
||||||
|
|
||||||
|
remove: endpoint<{ id: string }, void>(
|
||||||
|
"bookings",
|
||||||
|
"remove",
|
||||||
|
async ({ id }) => {
|
||||||
|
await client.delete(`/bookings/${id}`);
|
||||||
|
},
|
||||||
|
),
|
||||||
|
},
|
||||||
|
|
||||||
|
consignments: {
|
||||||
|
list: endpoint<void, PaginatedResponse<Freight.IConsignment>>(
|
||||||
|
"consignments",
|
||||||
|
"list",
|
||||||
|
async () => {
|
||||||
|
const { data } = await client.get("/consignments");
|
||||||
|
return unwrap(data);
|
||||||
|
},
|
||||||
|
),
|
||||||
|
|
||||||
|
get: endpoint<{ id: string }, Freight.IConsignment>(
|
||||||
|
"consignments",
|
||||||
|
"get",
|
||||||
|
async ({ id }) => {
|
||||||
|
const { data } = await client.get(`/consignments/${id}`);
|
||||||
|
return unwrap(data);
|
||||||
|
},
|
||||||
|
),
|
||||||
|
},
|
||||||
|
|
||||||
|
tracking: {
|
||||||
|
forConsignment: endpoint<
|
||||||
|
{ consignmentId: string },
|
||||||
|
Freight.ITrackingEvent[]
|
||||||
|
>("tracking", "forConsignment", async ({ consignmentId }) => {
|
||||||
|
const { data } = await client.get(`/tracking/${consignmentId}`);
|
||||||
|
return unwrap(data);
|
||||||
|
}),
|
||||||
|
},
|
||||||
|
|
||||||
|
fileUploadSettings: {
|
||||||
|
list: endpoint<void, FileUploadSetting[]>(
|
||||||
|
"file-upload-settings",
|
||||||
|
"list",
|
||||||
|
async () => {
|
||||||
|
const { data } = await client.get("/api/file-upload-settings");
|
||||||
|
return unwrap(data);
|
||||||
|
},
|
||||||
|
),
|
||||||
|
|
||||||
|
getById: endpoint<{ id: string }, FileUploadSetting>(
|
||||||
|
"file-upload-settings",
|
||||||
|
"getById",
|
||||||
|
async ({ id }) => {
|
||||||
|
const { data } = await client.get(`/api/file-upload-settings/${id}`);
|
||||||
|
return unwrap(data);
|
||||||
|
},
|
||||||
|
),
|
||||||
|
|
||||||
|
getByCode: endpoint<{ code: string }, FileUploadSetting>(
|
||||||
|
"file-upload-settings",
|
||||||
|
"getByCode",
|
||||||
|
async ({ code }) => {
|
||||||
|
const { data } = await client.get(
|
||||||
|
`/api/file-upload-settings/by-code/${encodeURIComponent(code)}`,
|
||||||
|
);
|
||||||
|
return unwrap(data);
|
||||||
|
},
|
||||||
|
),
|
||||||
|
|
||||||
|
create: endpoint<CreateFileUploadSettingDto, FileUploadSetting>(
|
||||||
|
"file-upload-settings",
|
||||||
|
"create",
|
||||||
|
async (payload) => {
|
||||||
|
const { data } = await client.post(
|
||||||
|
"/api/file-upload-settings",
|
||||||
|
payload,
|
||||||
|
);
|
||||||
|
return unwrap(data);
|
||||||
|
},
|
||||||
|
),
|
||||||
|
|
||||||
|
update: endpoint<
|
||||||
|
{ id: string; dto: UpdateFileUploadSettingDto },
|
||||||
|
FileUploadSetting
|
||||||
|
>("file-upload-settings", "update", async ({ id, dto }) => {
|
||||||
|
const { data } = await client.patch(
|
||||||
|
`/api/file-upload-settings/${id}`,
|
||||||
|
dto,
|
||||||
|
);
|
||||||
|
return unwrap(data);
|
||||||
|
}),
|
||||||
|
|
||||||
|
remove: endpoint<{ id: string }, void>(
|
||||||
|
"file-upload-settings",
|
||||||
|
"remove",
|
||||||
|
async ({ id }) => {
|
||||||
|
await client.delete(`/api/file-upload-settings/${id}`);
|
||||||
|
},
|
||||||
|
),
|
||||||
|
|
||||||
|
replaceFields: endpoint<
|
||||||
|
{ id: string; fields: CreateFileUploadFieldDto[] },
|
||||||
|
FileUploadField[]
|
||||||
|
>("file-upload-settings", "replaceFields", async ({ id, fields }) => {
|
||||||
|
const { data } = await client.put(
|
||||||
|
`/api/file-upload-settings/${id}/fields`,
|
||||||
|
fields,
|
||||||
|
);
|
||||||
|
return unwrap(data);
|
||||||
|
}),
|
||||||
|
|
||||||
|
addField: endpoint<
|
||||||
|
{ settingId: string; dto: CreateFileUploadFieldDto },
|
||||||
|
FileUploadField
|
||||||
|
>("file-upload-settings", "addField", async ({ settingId, dto }) => {
|
||||||
|
const { data } = await client.post(
|
||||||
|
`/api/file-upload-settings/${settingId}/fields`,
|
||||||
|
dto,
|
||||||
|
);
|
||||||
|
return unwrap(data);
|
||||||
|
}),
|
||||||
|
|
||||||
|
updateField: endpoint<
|
||||||
|
{ fieldId: string; dto: UpdateFileUploadFieldDto },
|
||||||
|
FileUploadField
|
||||||
|
>("file-upload-settings", "updateField", async ({ fieldId, dto }) => {
|
||||||
|
const { data } = await client.patch(
|
||||||
|
`/api/file-upload-settings/fields/${fieldId}`,
|
||||||
|
dto,
|
||||||
|
);
|
||||||
|
return unwrap(data);
|
||||||
|
}),
|
||||||
|
|
||||||
|
removeField: endpoint<{ fieldId: string }, void>(
|
||||||
|
"file-upload-settings",
|
||||||
|
"removeField",
|
||||||
|
async ({ fieldId }) => {
|
||||||
|
await client.delete(`/api/file-upload-settings/fields/${fieldId}`);
|
||||||
|
},
|
||||||
|
),
|
||||||
|
},
|
||||||
|
};
|
||||||
@@ -1,3 +1,4 @@
|
|||||||
|
import { QueryObserverOptions, UseQueryOptions } from "@tanstack/react-query";
|
||||||
import axios from "axios";
|
import axios from "axios";
|
||||||
|
|
||||||
export const client = axios.create({
|
export const client = axios.create({
|
||||||
@@ -24,3 +25,88 @@ client.interceptors.response.use(
|
|||||||
return Promise.reject(error);
|
return Promise.reject(error);
|
||||||
},
|
},
|
||||||
);
|
);
|
||||||
|
|
||||||
|
// ---------------------------------------------------------------------------
|
||||||
|
// Types
|
||||||
|
// ---------------------------------------------------------------------------
|
||||||
|
|
||||||
|
export type QueryConfig<T> = Omit<
|
||||||
|
UseQueryOptions<T, Error, T, readonly unknown[]>,
|
||||||
|
"queryKey" | "queryFn"
|
||||||
|
>;
|
||||||
|
|
||||||
|
export interface EndpointWithInput<TInput, TResponse> {
|
||||||
|
call(input: TInput): Promise<TResponse>;
|
||||||
|
queryKey(): readonly unknown[];
|
||||||
|
queryKey(input: TInput): readonly unknown[];
|
||||||
|
queryOptions(
|
||||||
|
config: { input: TInput } & QueryConfig<TResponse>,
|
||||||
|
): UseQueryOptions<TResponse, Error, TResponse, readonly unknown[]>;
|
||||||
|
}
|
||||||
|
|
||||||
|
export interface EndpointWithoutInput<TResponse> {
|
||||||
|
call(): Promise<TResponse>;
|
||||||
|
queryKey(): readonly unknown[];
|
||||||
|
queryOptions(
|
||||||
|
config?: QueryConfig<TResponse>,
|
||||||
|
): UseQueryOptions<TResponse, Error, TResponse, readonly unknown[]>;
|
||||||
|
}
|
||||||
|
|
||||||
|
export type Endpoint<TInput, TResponse> = TInput extends void
|
||||||
|
? EndpointWithoutInput<TResponse>
|
||||||
|
: EndpointWithInput<TInput, TResponse>;
|
||||||
|
|
||||||
|
// ---------------------------------------------------------------------------
|
||||||
|
// Builder
|
||||||
|
// ---------------------------------------------------------------------------
|
||||||
|
|
||||||
|
export function endpoint<TInput, TResponse>(
|
||||||
|
service: string,
|
||||||
|
action: string,
|
||||||
|
execute: (input: TInput) => Promise<TResponse>,
|
||||||
|
): Endpoint<TInput, TResponse> {
|
||||||
|
const call = (input: TInput) => execute(input);
|
||||||
|
|
||||||
|
const queryKey = (input?: TInput): readonly unknown[] => {
|
||||||
|
if (input === undefined) return [service, action] as const;
|
||||||
|
return [service, action, input] as const;
|
||||||
|
};
|
||||||
|
|
||||||
|
const queryOptions = (
|
||||||
|
config?: Record<string, unknown>,
|
||||||
|
): QueryObserverOptions<
|
||||||
|
TResponse,
|
||||||
|
Error,
|
||||||
|
TResponse,
|
||||||
|
TResponse,
|
||||||
|
readonly unknown[]
|
||||||
|
> => {
|
||||||
|
const input = config?.input as TInput | undefined;
|
||||||
|
const { input: _, ...rest } = config ?? {};
|
||||||
|
const key: readonly unknown[] =
|
||||||
|
input !== undefined ? [service, action, input] : [service, action];
|
||||||
|
return {
|
||||||
|
...rest,
|
||||||
|
queryKey: key,
|
||||||
|
queryFn: () => execute(input as TInput),
|
||||||
|
} as ReturnType<typeof queryOptions>;
|
||||||
|
};
|
||||||
|
|
||||||
|
return { call, queryKey, queryOptions } as Endpoint<TInput, TResponse>;
|
||||||
|
}
|
||||||
|
|
||||||
|
// ---------------------------------------------------------------------------
|
||||||
|
// Helpers
|
||||||
|
// ---------------------------------------------------------------------------
|
||||||
|
|
||||||
|
/** Some API endpoints return `{ data: T }`, others return `T` directly. */
|
||||||
|
export function unwrap<T>(response: { data: T } | T): T {
|
||||||
|
if (
|
||||||
|
response &&
|
||||||
|
typeof response === "object" &&
|
||||||
|
"data" in (response as object)
|
||||||
|
) {
|
||||||
|
return (response as { data: T }).data;
|
||||||
|
}
|
||||||
|
return response as T;
|
||||||
|
}
|
||||||
|
|||||||
426
packages/ui-common/src/components/SmartFileInput/index.tsx
Normal file
426
packages/ui-common/src/components/SmartFileInput/index.tsx
Normal file
@@ -0,0 +1,426 @@
|
|||||||
|
import React, { useState, useMemo, useRef } from "react";
|
||||||
|
import {
|
||||||
|
IFileUploadSetting,
|
||||||
|
IFileUploadField,
|
||||||
|
} from "@edr/types/freight";
|
||||||
|
import {
|
||||||
|
UploadCloud,
|
||||||
|
FileText,
|
||||||
|
Image as ImageIcon,
|
||||||
|
File,
|
||||||
|
Trash2,
|
||||||
|
AlertCircle,
|
||||||
|
CheckCircle2,
|
||||||
|
} from "lucide-react";
|
||||||
|
import { cn } from "../../lib/utils";
|
||||||
|
import { Button } from "../button";
|
||||||
|
|
||||||
|
export interface SmartFileInputProps {
|
||||||
|
/** The settings object containing features and their upload fields config. */
|
||||||
|
file: IFileUploadSetting;
|
||||||
|
/** Controlled value: maps each fileKey to the selected File or File[]. */
|
||||||
|
value?: Record<string, File | File[] | null>;
|
||||||
|
/** Callback triggered when any field's files change. */
|
||||||
|
onChange?: (value: Record<string, File | File[] | null>) => void;
|
||||||
|
/** External form errors mapped by fileKey. */
|
||||||
|
errors?: Record<string, 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;
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Helper to format file sizes in bytes to a human-readable string. */
|
||||||
|
function formatBytes(bytes: number, decimals = 2) {
|
||||||
|
if (bytes === 0) return "0 Bytes";
|
||||||
|
const k = 1024;
|
||||||
|
const dm = decimals < 0 ? 0 : decimals;
|
||||||
|
const sizes = ["Bytes", "KB", "MB", "GB"];
|
||||||
|
const i = Math.floor(Math.log(bytes) / Math.log(k));
|
||||||
|
return parseFloat((bytes / Math.pow(k, i)).toFixed(dm)) + " " + sizes[i];
|
||||||
|
}
|
||||||
|
|
||||||
|
/** 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)} />;
|
||||||
|
}
|
||||||
|
|
||||||
|
export function SmartFileInput({
|
||||||
|
file,
|
||||||
|
value,
|
||||||
|
onChange,
|
||||||
|
errors,
|
||||||
|
disabled = false,
|
||||||
|
variant = "default",
|
||||||
|
className,
|
||||||
|
}: SmartFileInputProps) {
|
||||||
|
// Local state to manage files when the component is used in an uncontrolled manner
|
||||||
|
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>>({});
|
||||||
|
|
||||||
|
// File input refs for programmatic clicks in minimal variant
|
||||||
|
const fileInputRefs = useRef<Record<string, HTMLInputElement | null>>({});
|
||||||
|
|
||||||
|
// Memoize fields sorted by the order property (ascending)
|
||||||
|
const sortedFields = useMemo(() => {
|
||||||
|
return [...file.fields].sort((a, b) => a.order - b.order);
|
||||||
|
}, [file.fields]);
|
||||||
|
|
||||||
|
// 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>);
|
||||||
|
}, [file.fields]);
|
||||||
|
|
||||||
|
// Resolve current files list for a field
|
||||||
|
const getFilesForField = (fieldKey: string): File[] => {
|
||||||
|
const val = value ? value[fieldKey] : internalFiles[fieldKey];
|
||||||
|
if (!val) return [];
|
||||||
|
return Array.isArray(val) ? val : [val];
|
||||||
|
};
|
||||||
|
|
||||||
|
const handleFilesChange = (fieldKey: string, newFiles: File[]) => {
|
||||||
|
const field = fieldsMap[fieldKey];
|
||||||
|
if (!field) return;
|
||||||
|
|
||||||
|
const newValue = field.isMultiple ? newFiles : (newFiles[0] || null);
|
||||||
|
|
||||||
|
if (onChange) {
|
||||||
|
const updatedValues = {
|
||||||
|
...(value || {}),
|
||||||
|
[fieldKey]: newValue,
|
||||||
|
};
|
||||||
|
onChange(updatedValues);
|
||||||
|
} else {
|
||||||
|
setInternalFiles((prev) => ({
|
||||||
|
...prev,
|
||||||
|
[fieldKey]: newFiles,
|
||||||
|
}));
|
||||||
|
}
|
||||||
|
};
|
||||||
|
|
||||||
|
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(/^\./, "")
|
||||||
|
);
|
||||||
|
|
||||||
|
let validIncoming: File[] = [];
|
||||||
|
let errorMsg = "";
|
||||||
|
|
||||||
|
for (const fileObj of incomingFiles) {
|
||||||
|
const ext = fileObj.name.split(".").pop()?.toLowerCase() || "";
|
||||||
|
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;
|
||||||
|
}
|
||||||
|
|
||||||
|
if (!isSizeValid) {
|
||||||
|
errorMsg = `File size exceeds the limit of ${field.maxSizeMb}MB`;
|
||||||
|
break;
|
||||||
|
}
|
||||||
|
|
||||||
|
validIncoming.push(fileObj);
|
||||||
|
}
|
||||||
|
|
||||||
|
if (errorMsg) {
|
||||||
|
setLocalErrors((prev) => ({ ...prev, [field.fileKey]: errorMsg }));
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
// Clear local error on successful file addition
|
||||||
|
setLocalErrors((prev) => {
|
||||||
|
const updated = { ...prev };
|
||||||
|
delete updated[field.fileKey];
|
||||||
|
return updated;
|
||||||
|
});
|
||||||
|
|
||||||
|
let newFilesList: File[] = [];
|
||||||
|
if (field.isMultiple) {
|
||||||
|
newFilesList = [...currentFiles, ...validIncoming].slice(0, maxAllowed);
|
||||||
|
if (currentFiles.length + validIncoming.length > maxAllowed) {
|
||||||
|
setLocalErrors((prev) => ({
|
||||||
|
...prev,
|
||||||
|
[field.fileKey]: `Only up to ${maxAllowed} files are allowed for this field. Excess files were ignored.`,
|
||||||
|
}));
|
||||||
|
}
|
||||||
|
} else {
|
||||||
|
newFilesList = validIncoming.slice(0, 1);
|
||||||
|
}
|
||||||
|
|
||||||
|
handleFilesChange(field.fileKey, newFilesList);
|
||||||
|
};
|
||||||
|
|
||||||
|
const handleDrag = (e: React.DragEvent, fieldKey: string, active: boolean) => {
|
||||||
|
e.preventDefault();
|
||||||
|
e.stopPropagation();
|
||||||
|
if (disabled) return;
|
||||||
|
setDragActive((prev) => ({ ...prev, [fieldKey]: active }));
|
||||||
|
};
|
||||||
|
|
||||||
|
const handleDrop = (e: React.DragEvent, field: IFileUploadField) => {
|
||||||
|
e.preventDefault();
|
||||||
|
e.stopPropagation();
|
||||||
|
if (disabled) return;
|
||||||
|
setDragActive((prev) => ({ ...prev, [field.fileKey]: false }));
|
||||||
|
|
||||||
|
if (e.dataTransfer.files && e.dataTransfer.files.length > 0) {
|
||||||
|
const filesArray = Array.from(e.dataTransfer.files);
|
||||||
|
processFiles(field, filesArray);
|
||||||
|
}
|
||||||
|
};
|
||||||
|
|
||||||
|
const handleFileSelect = (
|
||||||
|
e: React.ChangeEvent<HTMLInputElement>,
|
||||||
|
field: IFileUploadField
|
||||||
|
) => {
|
||||||
|
if (e.target.files && e.target.files.length > 0) {
|
||||||
|
const filesArray = Array.from(e.target.files);
|
||||||
|
processFiles(field, filesArray);
|
||||||
|
e.target.value = ""; // reset so same file can be selected again
|
||||||
|
}
|
||||||
|
};
|
||||||
|
|
||||||
|
const removeFile = (fieldKey: string, indexToRemove: number) => {
|
||||||
|
if (disabled) return;
|
||||||
|
const currentFiles = getFilesForField(fieldKey);
|
||||||
|
const updatedFiles = currentFiles.filter((_, idx) => idx !== indexToRemove);
|
||||||
|
|
||||||
|
const field = fieldsMap[fieldKey];
|
||||||
|
if (field && field.isRequired && updatedFiles.length === 0) {
|
||||||
|
setLocalErrors((prev) => ({
|
||||||
|
...prev,
|
||||||
|
[fieldKey]: "This file is required",
|
||||||
|
}));
|
||||||
|
} else {
|
||||||
|
setLocalErrors((prev) => {
|
||||||
|
const updated = { ...prev };
|
||||||
|
delete updated[fieldKey];
|
||||||
|
return updated;
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
handleFilesChange(fieldKey, updatedFiles);
|
||||||
|
};
|
||||||
|
|
||||||
|
return (
|
||||||
|
<div className={cn("flex flex-col gap-6", className)}>
|
||||||
|
{file.description && (
|
||||||
|
<div className="text-sm text-muted-foreground border-b border-border pb-3">
|
||||||
|
{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(",");
|
||||||
|
|
||||||
|
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>
|
||||||
|
|
||||||
|
{/* 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>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>
|
||||||
|
) : (
|
||||||
|
<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>
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
export default SmartFileInput;
|
||||||
@@ -4,6 +4,9 @@ export type { TableProps, TableColumn } from "./components/Table";
|
|||||||
export { FormField } from "./components/Form";
|
export { FormField } from "./components/Form";
|
||||||
export type { FormFieldProps } from "./components/Form";
|
export type { FormFieldProps } from "./components/Form";
|
||||||
|
|
||||||
|
export { default as SmartFileInput } from "./components/SmartFileInput";
|
||||||
|
export type { SmartFileInputProps } from "./components/SmartFileInput";
|
||||||
|
|
||||||
export { default as Modal } from "./components/Modal";
|
export { default as Modal } from "./components/Modal";
|
||||||
export type { ModalProps } from "./components/Modal";
|
export type { ModalProps } from "./components/Modal";
|
||||||
|
|
||||||
@@ -26,3 +29,4 @@ export * from "./components/card";
|
|||||||
export * from "./components/dropdown-menu";
|
export * from "./components/dropdown-menu";
|
||||||
export * from "./components/data-table";
|
export * from "./components/data-table";
|
||||||
export * from "./components/dialog";
|
export * from "./components/dialog";
|
||||||
|
export * from "./components/SmartFileInput";
|
||||||
|
|||||||
Reference in New Issue
Block a user