import React, { useCallback } from "react"; import { ArrayProperty, Entity, EntityCollection, FieldProps, ResolvedArrayProperty, ResolvedStringProperty, StorageConfig } from "../../types"; import { useDropzone } from "react-dropzone"; import { PreviewSize } from "../../preview"; import { FieldHelperText, LabelWithIcon } from "../components"; import { getIconForProperty, isReadOnly } from "../../util"; import { useSnackbarController, useStorageSource } from "../../hooks"; import { DragDropContext, Draggable, Droppable } from "@hello-pangea/dnd"; import { StorageFieldItem, useStorageUploadController } from "../../util/useStorageUploadController"; import { StorageUploadProgress } from "../components/StorageUploadProgress"; import { StorageItemPreview } from "../components/StorageItemPreview"; import { cn, fieldBackgroundDisabledMixin, fieldBackgroundHoverMixin, fieldBackgroundMixin, focusedMixin, Typography } from "@firecms/ui"; import { useClearRestoreValue } from "../useClearRestoreValue"; const dropZoneClasses = "box-border relative pt-[2px] items-center border border-transparent min-h-[254px] outline-none rounded-md duration-200 ease-[cubic-bezier(0.4,0,0.2,1)] focus:border-primary-solid"; const disabledClasses = "border-dotted-gray" const nonActiveDropClasses = "hover:bg-field-hover dark:hover:bg-field-hover-dark" const activeDropClasses = "pt-0 border-2 border-solid" const acceptDropClasses = "transition-colors duration-200 ease-[cubic-bezier(0,0,0.2,1)] border-2 border-solid border-green-500" const rejectDropClasses = "transition-colors duration-200 ease-[cubic-bezier(0,0,0.2,1)] border-2 border-solid border-red-500" type StorageUploadFieldProps = FieldProps; /** * Field that allows to upload files to Google Cloud Storage. * * This is one of the internal components that get mapped natively inside forms * and tables to the specified properties. * @group Form fields */ export function StorageUploadFieldBinding({ propertyKey, value, setValue, error, showError, autoFocus, tableMode, property, includeDescription, context, isSubmitting, }: StorageUploadFieldProps) { if (!context.entityId) throw new Error("StorageUploadFieldBinding: Entity id is null"); const storageSource = useStorageSource(context.collection); const disabled = isReadOnly(property) || !!property.disabled || isSubmitting; const { internalValue, setInternalValue, onFilesAdded, storage, onFileUploadComplete, storagePathBuilder, multipleFilesSupported } = useStorageUploadController({ entityValues: context.values, entityId: context.entityId, path: context.path, property, propertyKey, value, storageSource, disabled, onChange: setValue }); useClearRestoreValue({ property, value, setValue }); const entity: Entity = { id: context.entityId, values: context.values, path: context.path }; return ( <> {!tableMode && } ); } function FileDropComponent({ storage, collection, disabled, isDraggingOver, onFilesAdded, multipleFilesSupported, droppableProvided, autoFocus, internalValue, property, entity, onClear, metadata, storagePathBuilder, onFileUploadComplete, size, name, helpText }: { storage: StorageConfig, collection: EntityCollection, disabled: boolean, isDraggingOver: boolean, droppableProvided: any, onFilesAdded: (acceptedFiles: File[]) => void, multipleFilesSupported: boolean, autoFocus: boolean, internalValue: StorageFieldItem[], property: ResolvedStringProperty, onClear: (clearedStoragePathOrDownloadUrl: string) => void, metadata: any, entity: Entity; storagePathBuilder: (file: File) => string, onFileUploadComplete: (uploadedPath: string, entry: StorageFieldItem, fileMetadata?: any) => Promise, size: PreviewSize, name: string, helpText: string }) { const snackbarContext = useSnackbarController(); const { getRootProps, getInputProps, isDragActive, isDragAccept, isDragReject } = useDropzone({ accept: storage.acceptedFiles ? storage.acceptedFiles.map(e => ({ [e]: [] })).reduce((a, b) => ({ ...a, ...b }), {}) : undefined, disabled: disabled || isDraggingOver, noDragEventsBubbling: true, maxSize: storage.maxSize, onDrop: onFilesAdded, onDropRejected: (fileRejections, event) => { for (const fileRejection of fileRejections) { for (const error of fileRejection.errors) { snackbarContext.open({ type: "error", message: `Error uploading file: File is larger than ${storage.maxSize} bytes` }); } } } } ); return (
{internalValue.map((entry, index) => { let child: any; if (entry.storagePathOrDownloadUrl) { child = ( ); } else if (entry.file) { child = ( ); } return ( {(provided, snapshot) => (
{child}
)}
); }) } {droppableProvided.placeholder}
{helpText}
); } export interface StorageUploadProps { value: StorageFieldItem[]; collection: EntityCollection; setInternalValue: (v: StorageFieldItem[]) => void; name: string; property: ResolvedStringProperty | ResolvedArrayProperty; onChange: (value: string | string[] | null) => void; multipleFilesSupported: boolean; autoFocus: boolean; disabled: boolean; entity: Entity; storage: StorageConfig; onFilesAdded: (acceptedFiles: File[]) => void; storagePathBuilder: (file: File) => string; onFileUploadComplete: (uploadedPath: string, entry: StorageFieldItem, fileMetadata?: any) => Promise; } export function StorageUpload({ collection, property, name, value, setInternalValue, onChange, multipleFilesSupported, onFileUploadComplete, disabled, onFilesAdded, autoFocus, storage, entity, storagePathBuilder, }: StorageUploadProps) { if (multipleFilesSupported) { const arrayProperty = property as ResolvedArrayProperty; if (arrayProperty.of) { if (Array.isArray(arrayProperty.of)) { throw Error("Storage field using array must be of data type string"); } if (arrayProperty.of.dataType !== "string") { throw Error("Storage field using array must be of data type string"); } } else { throw Error("Storage field using array must be of data type string"); } } const metadata: Record | undefined = storage?.metadata; const size = multipleFilesSupported ? "small" : "medium"; const moveItem = useCallback((fromIndex: number, toIndex: number) => { if (!multipleFilesSupported) return; const newValue = [...value]; const item = newValue[fromIndex]; newValue.splice(fromIndex, 1); newValue.splice(toIndex, 0, item); setInternalValue(newValue); const fieldValue = newValue .filter(e => !!e.storagePathOrDownloadUrl) .map(e => e.storagePathOrDownloadUrl as string); onChange(fieldValue); }, [multipleFilesSupported, onChange, setInternalValue, value]); const onDragEnd = useCallback((result: any) => { // dropped outside the list if (!result.destination) { return; } moveItem(result.source.index, result.destination.index); }, [moveItem]) const onClear = useCallback((clearedStoragePathOrDownloadUrl: string) => { if (multipleFilesSupported) { const newValue: StorageFieldItem[] = value.filter(v => v.storagePathOrDownloadUrl !== clearedStoragePathOrDownloadUrl); onChange(newValue.filter(v => !!v.storagePathOrDownloadUrl).map(v => v.storagePathOrDownloadUrl as string)); setInternalValue(newValue); } else { onChange(null); setInternalValue([]); } }, [value, multipleFilesSupported, onChange]); const helpText = multipleFilesSupported ? "Drag 'n' drop some files here, or click to select files" : "Drag 'n' drop a file here, or click to select one"; const renderProperty: ResolvedStringProperty = multipleFilesSupported ? (property as ArrayProperty).of as ResolvedStringProperty : property as ResolvedStringProperty; return ( { const entry = value[rubric.source.index]; return (
); }} > {(provided, snapshot) => { return }}
); }