Skip to content
Snippets Groups Projects
Commit 61d4cf9e authored by Jose Manuel Serrano Amaut's avatar Jose Manuel Serrano Amaut
Browse files

[REF]: Refactor Dropzone, FileInputButton and core upload related methods to...

[REF]: Refactor Dropzone, FileInputButton and core upload related methods to set the server response inside of ExtFiles
parent 0ed55c80
Branches
No related tags found
No related merge requests found
Showing with 357 additions and 265 deletions
...@@ -221,6 +221,7 @@ const Dropzone: React.FC<DropzoneProps> = (props: DropzoneProps) => { ...@@ -221,6 +221,7 @@ const Dropzone: React.FC<DropzoneProps> = (props: DropzoneProps) => {
// setIsUploading(true); // setIsUploading(true);
//PREPARING stage //PREPARING stage
console.log("validateFilesFlag", validateFilesFlag); console.log("validateFilesFlag", validateFilesFlag);
onUploadStart?.(localFiles);
arrOfExtFilesInstances = arrOfExtFilesInstances =
ExtFileManager.setFileListMapPreparing( ExtFileManager.setFileListMapPreparing(
...@@ -251,8 +252,7 @@ const Dropzone: React.FC<DropzoneProps> = (props: DropzoneProps) => { ...@@ -251,8 +252,7 @@ const Dropzone: React.FC<DropzoneProps> = (props: DropzoneProps) => {
console.log("FileManagerLog after sleep", arrOfExtFilesInstances); console.log("FileManagerLog after sleep", arrOfExtFilesInstances);
//return; //return;
let serverResponses: Array<UploadResponse> = []; let serverResponses: Array<ExtFile> = [];
//Uplad files one by one //Uplad files one by one
for (let i = 0; i < arrOfExtFilesInstances.length; i++) { for (let i = 0; i < arrOfExtFilesInstances.length; i++) {
const currentExtFileInstance: ExtFileInstance = arrOfExtFilesInstances[i]; const currentExtFileInstance: ExtFileInstance = arrOfExtFilesInstances[i];
...@@ -282,13 +282,14 @@ const Dropzone: React.FC<DropzoneProps> = (props: DropzoneProps) => { ...@@ -282,13 +282,14 @@ const Dropzone: React.FC<DropzoneProps> = (props: DropzoneProps) => {
//UPLOADING => UPLOAD() //UPLOADING => UPLOAD()
//upload one file and notify about change //upload one file and notify about change
let uploadResponse: UploadResponse; let uploadResponse: ExtFile;
if (fakeUpload) { if (fakeUpload) {
uploadResponse = await fakeFuiUpload( uploadResponse = await fakeFuiUpload(
currentExtFileInstance, currentExtFileInstance,
DropzoneLocalizer DropzoneLocalizer
); );
let fakeProgress = 0; let fakeProgress = 0;
while (fakeProgress < 100) { while (fakeProgress < 100) {
fakeProgress += getRandomInt(21, 35); fakeProgress += getRandomInt(21, 35);
...@@ -313,7 +314,7 @@ const Dropzone: React.FC<DropzoneProps> = (props: DropzoneProps) => { ...@@ -313,7 +314,7 @@ const Dropzone: React.FC<DropzoneProps> = (props: DropzoneProps) => {
} }
} }
const { uploadedFile } = uploadResponse; const uploadedFile = uploadResponse;
console.log("fake uploadResponse uploadedFile", uploadedFile); console.log("fake uploadResponse uploadedFile", uploadedFile);
//update instances //update instances
...@@ -335,18 +336,22 @@ const Dropzone: React.FC<DropzoneProps> = (props: DropzoneProps) => { ...@@ -335,18 +336,22 @@ const Dropzone: React.FC<DropzoneProps> = (props: DropzoneProps) => {
console.log( console.log(
"pre sanitizeArrExtFile", "pre sanitizeArrExtFile",
arrOfExtFilesInstances.map((F) => {return{status:F.uploadStatus,message:F.uploadMessage}}) arrOfExtFilesInstances.map((F) => {
return { status: F.uploadStatus, message: F.uploadMessage };
})
); );
//CHANGE //CHANGE
if (!(currentExtFileInstance.uploadStatus === "aborted")) if (!(currentExtFileInstance.uploadStatus === "aborted"))
await sleepTransition(); await sleepTransition();
console.log( console.log(
"pre sanitizeArrExtFile", "pre sanitizeArrExtFile",
arrOfExtFilesInstances.map((F) => {return{status:F.uploadStatus,message:F.uploadMessage}}) arrOfExtFilesInstances.map((F) => {
return { status: F.uploadStatus, message: F.uploadMessage };
})
); );
handleFilesChange(sanitizeArrExtFile(arrOfExtFilesInstances), true); handleFilesChange(sanitizeArrExtFile(arrOfExtFilesInstances), true);
if (uploadedFile.uploadStatus === "error") { if (uploadedFile.uploadStatus === "error") {
...@@ -369,7 +374,9 @@ const Dropzone: React.FC<DropzoneProps> = (props: DropzoneProps) => { ...@@ -369,7 +374,9 @@ const Dropzone: React.FC<DropzoneProps> = (props: DropzoneProps) => {
setLocalMessage( setLocalMessage(
finishUploadMessenger(missingUpload - totalRejected, totalRejected) finishUploadMessenger(missingUpload - totalRejected, totalRejected)
); );
setTimeout(() => {
setIsUploading(false); setIsUploading(false);
}, 2000);
}; };
const handleAbortUpload = () => { const handleAbortUpload = () => {
......
...@@ -31,51 +31,6 @@ export interface DropzoneFullProps extends OverridableComponentProps { ...@@ -31,51 +31,6 @@ export interface DropzoneFullProps extends OverridableComponentProps {
*/ */
value?: ExtFile[]; value?: ExtFile[];
/////////////// STYLING ///////////
/**
* The background color for dropzone container,
* @default 'transparent'
*/
backgroundColor?: string;
/**
* The min height of the container in string format
* If the value is given un number format "px" will be assumed
* @default "190px"
*
* examples:
* "50vh"
* "20%"
* "40em"
* "1rem"
*/
minHeight?: string | number;
/////////////// DISPLAY SETTINGS ///////////
/**
* If false, hides the dropzone footer
* By default is true
*/
footer?: boolean;
/**
* If false, hides the dropzone header
* By default is true
*/
header?: boolean;
/**
* The label to place when no files were selected
*/
label?: string;
/**
* The language to be used in Dropzone labels
* Currently only English, French , Portuguese, Chinnese (traditional and simplyfied), Russian and Spanish are supported
* @default "EN-en"
*/
localization?: Localization;
/**
* If true, will show a ripple everytime
* the user drops files or selects files
*/
disableRipple?: boolean;
/////////////// VALIDATION STAGE /////////////// /////////////// VALIDATION STAGE ///////////////
/** /**
* The max file size allowed in bytes * The max file size allowed in bytes
...@@ -127,37 +82,6 @@ export interface DropzoneFullProps extends OverridableComponentProps { ...@@ -127,37 +82,6 @@ export interface DropzoneFullProps extends OverridableComponentProps {
* This flag will only work if validation is active. * This flag will only work if validation is active.
*/ */
cleanFiles?: boolean; cleanFiles?: boolean;
///////// INPUT
/**
* If true, the dropzone component itself will be clickable
* If false, the file dialog will not be opened
* @default true
*/
clickable?: boolean;
/**
* The behaviour when new files are selected or dropped
* @default 'add'
*/
behaviour?: 'add' | 'replace';
/**
* If `true`, the component is disabled.
* @default false
*/
disabled?: boolean;
/**
* If `true`, the drop operation will be performed in a layer that covers the complete component container.
* @default true
*/
dropOnLayer?: boolean;
/**
* Method for performing specific tasks on drag enter operations
*/
onDragEnter?: (evt: React.DragEvent<HTMLDivElement>) => void;
/**
* Method for performing specific tasks on drag leave operations
*/
onDragLeave?: (evt: React.DragEvent<HTMLDivElement>) => void;
/////////////// UPLOAD STAGE /////////////// /////////////// UPLOAD STAGE ///////////////
/** /**
...@@ -180,16 +104,66 @@ export interface DropzoneFullProps extends OverridableComponentProps { ...@@ -180,16 +104,66 @@ export interface DropzoneFullProps extends OverridableComponentProps {
* Unlike Onchange, onUploadStart will only return a list of files thta are candidates to be uploaded, * Unlike Onchange, onUploadStart will only return a list of files thta are candidates to be uploaded,
* in case they are valid or upload status is "error" * in case they are valid or upload status is "error"
*/ */
onUploadStart?: (files: ExtFile[]) => void; onUploadStart?: (extFiles: ExtFile[]) => void;
/** /**
* This event returns as first aparameter the list of responses for each file following the structure: * This event returns as first aparameter the list of responses for each file following the structure:
* responses = [ * responses = [
* {id: <the file id>, serverResponse: the server response} * {id: <the file id>, serverResponse: the server response}
* ] * ]
*/ */
onUploadFinish?: (responses: UploadResponse[]) => void; onUploadFinish?: (extFiles: ExtFile[]) => void;
/////////////// STYLING ///////////
/**
* The background color for dropzone container,
* @default 'transparent'
*/
backgroundColor?: string;
/**
* The min height of the container in string format
* If the value is given un number format "px" will be assumed
* @default "190px"
*
* examples:
* "50vh"
* "20%"
* "40em"
* "1rem"
*/
minHeight?: string | number;
// LABEL
/**
* The label to place when no files were selected
*/
label?: string;
//LOCALIZATION
/**
* The language to be used in Dropzone labels
* @default "EN-en"
*/
localization?: Localization;
//RIPPLE
/**
* If true, will not show a ripple effect everytime
* the user drops files or clicks the dropzone for selecting files
* @default false
*/
disableRipple?: boolean;
/**
* Method for performing specific tasks on drag enter operations
*/
onDragEnter?: (evt: React.DragEvent<HTMLDivElement>) => void;
/**
* Method for performing specific tasks on drag leave operations
*/
onDragLeave?: (evt: React.DragEvent<HTMLDivElement>) => void;
//ACTION BUTTONS
/** /**
* The configuration needed for uploading the files. * The configuration needed for uploading the files.
* When "uploadConfig" is not given or uploadConfig.url is undefined * When "uploadConfig" is not given or uploadConfig.url is undefined
...@@ -198,15 +172,58 @@ export interface DropzoneFullProps extends OverridableComponentProps { ...@@ -198,15 +172,58 @@ export interface DropzoneFullProps extends OverridableComponentProps {
*/ */
actionButtons?: DropzoneActions; actionButtons?: DropzoneActions;
//advancedConfig?: DropzoneAdvancedConfig; ///////// DROP LAYER
/**
* If `true`, the drop operation will be performed in a layer that covers the complete component container.
* @default true
*/
dropOnLayer?: boolean;
// HEADER AND FOOTER
/**
* If false, hides the dropzone footer
* @default true
*/
footer?: boolean;
/**
* If false, hides the dropzone header
* @default true
*/
header?: boolean;
/**
* Configuration related to the dropzone header
*/
headerConfig?: HeaderConfig; headerConfig?: HeaderConfig;
/**
* Configuration related to the dropzone footer
*/
footerConfg?: FooterConfig; footerConfg?: FooterConfig;
//DISABLED
/**
* If `true`, the component is disabled.
* @default false
*/
disabled?: boolean;
//CLICKABLE
/**
* If true, the dropzone component itself will be clickable
* If false, the file dialog will not be opened
* @default true
*/
clickable?: boolean;
// ADD OR REPLACE
/**
* The behaviour when new files are selected or dropped
* @default 'add'
*/
behaviour?: 'add' | 'replace';
} }
export type HeaderItems = { export type HeaderConfig = {
customHeader?: JSX.Element;
deleteFiles?: boolean; deleteFiles?: boolean;
cleanFiles?: boolean; cleanFiles?: boolean;
uploadFiles?: boolean; uploadFiles?: boolean;
...@@ -214,19 +231,8 @@ export type HeaderItems = { ...@@ -214,19 +231,8 @@ export type HeaderItems = {
maxFileSize?: boolean; maxFileSize?: boolean;
validFilesCount?: boolean; validFilesCount?: boolean;
} }
export interface HeaderConfigMap extends OverridableComponentProps {
customHeader?: JSX.Element; export type FooterConfig = {
}
export type HeaderConfig =
{
[P in keyof HeaderConfigMap]: HeaderConfigMap[P]
} & {
[H in keyof HeaderItems]: HeaderItems[H]
}
export interface FooterConfigMap extends OverridableComponentProps {
customFooter?: JSX.Element;
}
export type FooterItems = {
/** /**
* Allowed types: .png,image/* * Allowed types: .png,image/*
*/ */
...@@ -243,13 +249,7 @@ export type FooterItems = { ...@@ -243,13 +249,7 @@ export type FooterItems = {
* *
*/ */
noMissingFilesLabel?: boolean; noMissingFilesLabel?: boolean;
} customFooter?: JSX.Element;
export type FooterConfig =
{
[P in keyof FooterConfigMap]: FooterConfigMap[P]
} & {
[H in keyof FooterItems]: FooterItems[H]
} }
...@@ -273,19 +273,6 @@ export interface DropzoneActions { ...@@ -273,19 +273,6 @@ export interface DropzoneActions {
} }
export interface AdvancedConfigItem {
style?: React.CSSProperties;
className?: string;
}
export type DropzoneAdvancedConfig = {
dropzoneLayer: any;
dropzoneContainer: any;
dropzoneLabel: any;
}
type DefDivProps = React.HTMLProps<HTMLDivElement>; type DefDivProps = React.HTMLProps<HTMLDivElement>;
type DivPropsOmitDropzoneFullProps = Omit<DefDivProps, keyof DropzoneFullProps>; type DivPropsOmitDropzoneFullProps = Omit<DefDivProps, keyof DropzoneFullProps>;
...@@ -308,3 +295,18 @@ export const defaultDrozoneProps: DropzoneProps = ...@@ -308,3 +295,18 @@ export const defaultDrozoneProps: DropzoneProps =
footer: true, footer: true,
value: [], value: [],
} }
/*
export interface AdvancedConfigItem {
style?: React.CSSProperties;
className?: string;
}
export type DropzoneAdvancedConfig = {
dropzoneLayer: any;
dropzoneContainer: any;
dropzoneLabel: any;
}
*/
\ No newline at end of file
...@@ -9,14 +9,18 @@ import { ...@@ -9,14 +9,18 @@ import {
fakeFuiUpload, fakeFuiUpload,
fileListToExtFileArray, fileListToExtFileArray,
FileValidatorProps, FileValidatorProps,
getRandomInt,
//FunctionLabel, //FunctionLabel,
handleClickInput, handleClickInput,
instantPreparingToUploadOne, instantPreparingToUploadOne,
isUploadAbleExtFile,
isValidateActive, isValidateActive,
LocalLabels, LocalLabels,
sanitizeArrExtFile,
sleepPreparing, sleepPreparing,
sleepTransition, sleepTransition,
toUploadableExtFileList, toUploadableExtFileList,
unexpectedErrorUploadResult,
UploadConfig, UploadConfig,
uploadExtFile, uploadExtFile,
UploadResponse, UploadResponse,
...@@ -134,36 +138,48 @@ const FileInputButton: React.FC<FileInputButtonProps> = ( ...@@ -134,36 +138,48 @@ const FileInputButton: React.FC<FileInputButtonProps> = (
* @returns nothing * @returns nothing
*/ */
const uploadfiles = async (localFiles: ExtFile[]): Promise<void> => { const uploadfiles = async (localFiles: ExtFile[]): Promise<void> => {
if (!url) return; //set uploading flag to true
setIsUploading(true); setIsUploading(true);
print_manager(localFiles, "start");
// set flag to true
// recieve on the new list
// initialize new list of ExtFileInstances
let arrOfExtFilesInstances: ExtFileInstance[] = [];
//avoid to call upload if not allowed //avoid to call upload if not allowed
if (isUploading || localFiles.length === 0 || !arrOfExtFilesInstances) { // flag is already true or there isnt files
//url was not provided
if (isUploading || localFiles.length === 0 || !url) {
setIsUploading(false);
return; return;
} }
// initialize a new list of ExtFileInstances
let arrOfExtFilesInstances: ExtFileInstance[] = [];
const totalNumber: number = localFiles.length; const totalNumber: number = localFiles.length;
const missingUpload: number = localFiles.filter((x: ExtFile) => { console.log("upload start: totalNumber", totalNumber);
return (
(!validateFilesFlag || (validateFilesFlag && x.valid)) && const missingUpload: number = localFiles.filter((extFile: ExtFile) =>
x.uploadStatus !== "success" isUploadAbleExtFile(extFile, validateFilesFlag)
); ).length;
}).length;
console.log("upload start: missingUpload", missingUpload);
let totalRejected: number = 0; let totalRejected: number = 0;
let currentCountUpload: number = 0; let currentCountUpload: number = 0;
/* const uploadingMessenger: FunctionLabel =
DropzoneLocalizer.uploadingMessage as FunctionLabel; */
//no missing to upload
if (!(missingUpload > 0)) {
console.log("upload start: noFilesMessage", missingUpload);
//setLocalMessage(DropzoneLocalizer.noFilesMessage as string);
setIsUploading(false);
return;
}
//setLocalMessage(uploadingMessenger(`${missingUpload}/${totalNumber}`));
// setIsUploading(true); // setIsUploading(true);
//PREPARING stage //PREPARING stage
//use methods to update on static class console.log("validateFilesFlag", validateFilesFlag);
//obtain a fresher dui file list
console.log("***** before setFileListMapPreparing");
console.table(localFiles);
arrOfExtFilesInstances = arrOfExtFilesInstances =
ExtFileManager.setFileListMapPreparing( ExtFileManager.setFileListMapPreparing(
inputButtonId, inputButtonId,
...@@ -172,8 +188,6 @@ const FileInputButton: React.FC<FileInputButtonProps> = ( ...@@ -172,8 +188,6 @@ const FileInputButton: React.FC<FileInputButtonProps> = (
cleanOnUpload as boolean cleanOnUpload as boolean
) || []; ) || [];
console.log("***** FileManagerLog setFileListMapPreparing");
console.table(arrOfExtFilesInstances);
const newExtFileLocal: ExtFile[] = [...arrOfExtFilesInstances].map((x) => const newExtFileLocal: ExtFile[] = [...arrOfExtFilesInstances].map((x) =>
x.toExtFile() x.toExtFile()
); );
...@@ -191,41 +205,59 @@ const FileInputButton: React.FC<FileInputButtonProps> = ( ...@@ -191,41 +205,59 @@ const FileInputButton: React.FC<FileInputButtonProps> = (
//AWAIT when preparing time is given //AWAIT when preparing time is given
//general sleep for all files //general sleep for all files
await sleepPreparing(preparingTime); await sleepPreparing(preparingTime);
// workaround for preventing getting the uploadStatus as undefined
/* arrOfExtFilesInstances.forEach((F) => {
F.uploadStatus = "preparing";
}); */
//variable for storing responses
//console.log("uploadfiles after sleep response",response);
console.log("FileManagerLog after sleep", arrOfExtFilesInstances); console.log("FileManagerLog after sleep", arrOfExtFilesInstances);
//return; //return;
let serverResponses: Array<UploadResponse> = []; let serverResponses: Array<ExtFile> = [];
for (let i = 0; i < arrOfExtFilesInstances.length; i++) { for (let i = 0; i < arrOfExtFilesInstances.length; i++) {
const currentExtFileInstance: ExtFileInstance = arrOfExtFilesInstances[i]; const currentExtFileInstance: ExtFileInstance = arrOfExtFilesInstances[i];
console.log( console.log(
"FileManagerLog currentExtFileInstance " + i, "FileManagerLog currentExtFileInstance " + i,
currentExtFileInstance currentExtFileInstance
); );
if (currentExtFileInstance.uploadStatus === "preparing") { if (
currentExtFileInstance.uploadStatus === "preparing" &&
!currentExtFileInstance.extraData?.deleted
) {
//set stage to "uploading" in one file and notify change //set stage to "uploading" in one file and notify change
// PREPARING => UPLOADING // PREPARING => UPLOADING
await sleepTransition();
instantPreparingToUploadOne(currentExtFileInstance); instantPreparingToUploadOne(currentExtFileInstance);
//messge in footer
/* setLocalMessage( /* setLocalMessage(
uploadingMessenger(`${++currentCountUpload}/${missingUpload}`) uploadingMessenger(`${++currentCountUpload}/${missingUpload}`)
); */ ); */
//CHANGE
handleFilesChange([...arrOfExtFilesInstances], true); //CHANGE FILES
handleFilesChange(sanitizeArrExtFile(arrOfExtFilesInstances), true);
//UPLOADING => UPLOAD() //UPLOADING => UPLOAD()
//upload one file and notify about change //upload one file and notify about change
let uploadResponse: UploadResponse; let uploadResponse: ExtFile;
if (fakeUpload) {
uploadResponse = await fakeFuiUpload(
currentExtFileInstance,
DropzoneLocalizer
);
let fakeProgress = 0;
while (fakeProgress < 100) {
fakeProgress += getRandomInt(21, 35);
currentExtFileInstance.progress =
fakeProgress > 100 ? 100 : fakeProgress;
await sleepTransition(1000);
handleFilesChange(sanitizeArrExtFile(arrOfExtFilesInstances), true);
}
} else {
try { try {
uploadResponse = fakeUpload uploadResponse = await uploadExtFile(
? await fakeFuiUpload(currentExtFileInstance, DropzoneLocalizer)
: await uploadExtFile(
currentExtFileInstance, currentExtFileInstance,
url, url,
method, method,
...@@ -233,58 +265,75 @@ const FileInputButton: React.FC<FileInputButtonProps> = ( ...@@ -233,58 +265,75 @@ const FileInputButton: React.FC<FileInputButtonProps> = (
uploadLabel uploadLabel
); );
} catch (error) { } catch (error) {
uploadResponse = { uploadResponse = unexpectedErrorUploadResult(
id: currentExtFileInstance.id, currentExtFileInstance.toExtFile()
serverResponse: { );
success: false, }
message: "Error on upload: unexpected error " + error,
payload: {},
},
uploadedFile: { ...currentExtFileInstance },
};
} }
const { uploadedFile } = uploadResponse; const uploadedFile = uploadResponse;
console.log("fake uploadResponse uploadedFile", uploadedFile);
//update instances //update instances
currentExtFileInstance.uploadStatus = uploadedFile.uploadStatus; currentExtFileInstance.uploadStatus = uploadedFile.uploadStatus;
currentExtFileInstance.uploadMessage = uploadedFile.uploadMessage; currentExtFileInstance.uploadMessage = uploadedFile.uploadMessage;
//add fake progress only on fakeupload
if (fakeUpload) {
console.log( console.log(
"Adding fake progress", "fake uploadResponse currentExtFileInstance",
fakeUpload, currentExtFileInstance
uploadedFile.progress
); );
currentExtFileInstance.progress = uploadedFile.progress; console.log(
} "fake uploadResponse currentExtFileInstance",
currentExtFileInstance.uploadStatus
);
console.log(
"fake uploadResponse currentExtFileInstance",
currentExtFileInstance.uploadMessage
);
console.log(
"pre sanitizeArrExtFile",
arrOfExtFilesInstances.map((F) => {
return { status: F.uploadStatus, message: F.uploadMessage };
})
);
//CHANGE //CHANGE
if (!(currentExtFileInstance.uploadStatus === "aborted")) if (!(currentExtFileInstance.uploadStatus === "aborted"))
await sleepTransition(); await sleepTransition();
handleFilesChange( console.log(
arrOfExtFilesInstances.map((x: ExtFileInstance) => x.toExtFile()), "pre sanitizeArrExtFile",
true arrOfExtFilesInstances.map((F) => {
return { status: F.uploadStatus, message: F.uploadMessage };
})
); );
handleFilesChange(sanitizeArrExtFile(arrOfExtFilesInstances), true);
if (uploadedFile.uploadStatus === "error") { if (uploadedFile.uploadStatus === "error") {
totalRejected++; totalRejected++;
} }
serverResponses.push(uploadResponse); serverResponses.push(uploadResponse);
} else {
handleFilesChange(sanitizeArrExtFile(arrOfExtFilesInstances), true);
} }
} }
handleFilesChange(sanitizeArrExtFile(arrOfExtFilesInstances), true);
// upload group finished :D // upload group finished :D
onUploadFinish?.(serverResponses); onUploadFinish?.(serverResponses);
/*
/* const finishUploadMessenger: FunctionLabel = const finishUploadMessenger: FunctionLabel =
DropzoneLocalizer.uploadFinished as FunctionLabel; DropzoneLocalizer.uploadFinished as FunctionLabel;
setLocalMessage( setLocalMessage(
finishUploadMessenger(missingUpload - totalRejected, totalRejected) finishUploadMessenger(missingUpload - totalRejected, totalRejected)
); */ ); */
setTimeout(() => {
setIsUploading(false); setIsUploading(false);
}, 2000);
}; };
/** /**
* Performs the changes in the FuiFile list. * Performs the changes in the FuiFile list.
......
...@@ -74,17 +74,14 @@ interface InputButtonFullProps { ...@@ -74,17 +74,14 @@ interface InputButtonFullProps {
* ``` * ```
*/ */
validator?: (f: File) => CustomValidateFileResponse; validator?: (f: File) => CustomValidateFileResponse;
/** /**
* Flag that indicates that dropzone will automatically remove non valid files. * Flag that indicates that dropzone will automatically remove non valid files.
* This will happen every time user drops files or selects files from file dialog. * This will happen every time user drops files or selects files from file dialog.
* This flag will only work if validation is active. * This flag will only work if validation is active.
*/ */
autoClean?: boolean; autoClean?: boolean;
/**
* The behaviour when new files are selected or dropped
* @default 'add'
*/
behaviour?: 'add' | 'replace';
/////////////// UPLOAD STAGE /////////////// /////////////// UPLOAD STAGE ///////////////
/** /**
* The configuration needed for uploading the files. * The configuration needed for uploading the files.
...@@ -106,17 +103,16 @@ interface InputButtonFullProps { ...@@ -106,17 +103,16 @@ interface InputButtonFullProps {
* Unlike Onchange, onUploadStart will only return a list of files thta are candidates to be uploaded, * Unlike Onchange, onUploadStart will only return a list of files thta are candidates to be uploaded,
* in case they are valid or upload status is "error" * in case they are valid or upload status is "error"
*/ */
onUploadStart?: (files: ExtFile[]) => void; onUploadStart?: (extFiles: ExtFile[]) => void;
/** /**
* This event returns as first aparameter the list of responses for each file following the structure: * This event returns as first aparameter the list of responses for each file following the structure:
* responses = [ * responses = [
* {id: <the file id>, serverResponse: the server response} * {id: <the file id>, serverResponse: the server response}
* ] * ]
*/ */
onUploadFinish?: (responses: UploadResponse[]) => void; onUploadFinish?: (extFiles: ExtFile[]) => void;
//ACTION BUTTONS
/** /**
* The configuration needed for uploading the files. * The configuration needed for uploading the files.
* When "uploadConfig" is not given or uploadConfig.url is undefined * When "uploadConfig" is not given or uploadConfig.url is undefined
...@@ -124,6 +120,12 @@ interface InputButtonFullProps { ...@@ -124,6 +120,12 @@ interface InputButtonFullProps {
* and uploadOnDrop flag will not work * and uploadOnDrop flag will not work
*/ */
actionButtons?: DropzoneActions; actionButtons?: DropzoneActions;
// ADD OR REPLACE
/**
* The behaviour when new files are selected or dropped
* @default 'add'
*/
behaviour?: 'add' | 'replace';
} }
type MaterialButtonPropsOmitInputButtonFullProps = Omit<MaterialButtonProps, keyof InputButtonFullProps>; type MaterialButtonPropsOmitInputButtonFullProps = Omit<MaterialButtonProps, keyof InputButtonFullProps>;
......
...@@ -29,7 +29,9 @@ export declare type ExtFile = { ...@@ -29,7 +29,9 @@ export declare type ExtFile = {
* The size of the file. Used mostly for displaying file data from server. * The size of the file. Used mostly for displaying file data from server.
*/ */
size?: number; size?: number;
/**
* Link, URI or string representation of an image
*/
imageUrl?: string; imageUrl?: string;
/** /**
* a flag that determines whether the file is valid, not valid or it is not validated. * a flag that determines whether the file is valid, not valid or it is not validated.
......
...@@ -18,7 +18,7 @@ export declare type UploadResponse = { ...@@ -18,7 +18,7 @@ export declare type UploadResponse = {
} }
export type ServerResponse = { export type ServerResponse = {
success: boolean; success: boolean;
message: string; message?: string;
payload: any; payload?: any;
} }
...@@ -22,16 +22,13 @@ export const UNEXPECTED_ERROR_RESPONSE = { ...@@ -22,16 +22,13 @@ export const UNEXPECTED_ERROR_RESPONSE = {
payload: {} payload: {}
} }
export const NO_XHR_PROVIDED_ERROR = (extFile: ExtFile): UploadResponse => { export const NO_XHR_PROVIDED_ERROR = (extFile: ExtFile): ExtFile => {
return { return {
uploadedFile:
{
...extFile, ...extFile,
uploadMessage: "Unable to upload. xhr object was not provided", uploadMessage: "Unable to upload. xhr object was not provided",
uploadStatus: "error" uploadStatus: "error",
},
id: extFile.id, serverResponse: { success: false, }
serverResponse: {}
} }
} }
\ No newline at end of file
...@@ -29,16 +29,13 @@ export const JsonParseResponse = (xhr: XMLHttpRequest): ServerResponse => { ...@@ -29,16 +29,13 @@ export const JsonParseResponse = (xhr: XMLHttpRequest): ServerResponse => {
export const makeSuccessUploadResponse = ( export const makeSuccessUploadResponse = (
extFile: ExtFile, extFile: ExtFile,
responseFui: ServerResponse responseFui: ServerResponse
): UploadResponse => { ): ExtFile => {
return { return {
id: extFile.id,
serverResponse: responseFui,
uploadedFile:
{
...extFile, ...extFile,
serverResponse: responseFui,
uploadMessage: responseFui.message, uploadMessage: responseFui.message,
uploadStatus: "success" uploadStatus: "success"
},
} }
} }
...@@ -46,17 +43,13 @@ export const makeSuccessUploadResponse = ( ...@@ -46,17 +43,13 @@ export const makeSuccessUploadResponse = (
export const makeErrorUploadResponse = ( export const makeErrorUploadResponse = (
extFile: ExtFile, extFile: ExtFile,
responseFui: ServerResponse responseFui: ServerResponse
): UploadResponse => { ): ExtFile => {
console.log("makeErrorUploadResponse", extFile, responseFui); console.log("makeErrorUploadResponse", extFile, responseFui);
return { return {
id: extFile.id,
serverResponse: responseFui,
uploadedFile:
{
...extFile, ...extFile,
uploadMessage: responseFui.message, uploadMessage: responseFui.message,
uploadStatus: "error" uploadStatus: "error",
}, serverResponse: responseFui,
} }
} }
...@@ -100,7 +100,7 @@ export const uploadExtFile = async ( ...@@ -100,7 +100,7 @@ export const uploadExtFile = async (
method?: Method, method?: Method,
headers?: Record<string, string>, headers?: Record<string, string>,
uploadLabel?: string, uploadLabel?: string,
): Promise<UploadResponse> => { ): Promise<ExtFile> => {
return new Promise(async (resolve, reject) => { return new Promise(async (resolve, reject) => {
try { try {
const uploader: XMLHttpRequest | undefined = extFile.xhr; const uploader: XMLHttpRequest | undefined = extFile.xhr;
......
import { ExtFile, ExtFileInstance, ServerResponse, UploadResponse, UPLOADSTATUS } from "../types" import { ExtFile, ExtFileInstance, ServerResponse, UploadResponse, UPLOADSTATUS } from "../types"
export const unexpectedErrorUploadResult = (extFile: ExtFile): UploadResponse => { export const unexpectedErrorUploadResult = (extFile: ExtFile): ExtFile => {
return { return {
id: extFile.id,
uploadedFile:
{
...extFile, ...extFile,
uploadMessage: "Unexpected error", uploadMessage: "Unexpected error",
uploadStatus: "error" uploadStatus: "error",
},
serverResponse: { serverResponse: {
success: false, success: false,
message: "Error on upload: unexpected error ", message: "Error on upload: unexpected error ",
......
...@@ -108,7 +108,51 @@ export const uploadOneExtFile = ( ...@@ -108,7 +108,51 @@ export const uploadOneExtFile = (
export const fakeFuiUpload = ( export const fakeFuiUpload = (
extFileInstance: ExtFileInstance, extFileInstance: ExtFileInstance,
DropzoneLocalizer = DropzoneLocalizerSelector("EN-en") DropzoneLocalizer = DropzoneLocalizerSelector("EN-en")
): Promise<ExtFile> => {
const extFile:ExtFile = extFileInstance.toExtFile();
return new Promise((resolve, reject) => {
setTimeout(() => {
const randomNumber: number = Math.floor(Math.random() * 10);
if (randomNumber % 2 === 0) {
const success = true;
const message = DropzoneLocalizer.fakeuploadsuccess as string;
const payload = { url: "" };
resolve({
...extFile,
serverResponse: { success, message, payload },
uploadStatus: "success",
uploadMessage: message,
});
} else {
const success = false;
const message = DropzoneLocalizer.fakeUploadError as string;
const payload = {};
resolve({
...extFile,
serverResponse: { success, message, payload },
uploadStatus: "error",
uploadMessage: message,
});
}
}, 1700);
});
};
/**
*
* @param extFile the extFile to upload
* @param DropzoneLocalizer the localization
* @returns a duiUploadResponse object that describes the result
*/
export const fakeFuiUploadExtFile = (
extFileInstance: ExtFileInstance,
DropzoneLocalizer = DropzoneLocalizerSelector("EN-en")
): Promise<UploadResponse> => { ): Promise<UploadResponse> => {
const extFile:ExtFile = extFileInstance.toExtFile(); const extFile:ExtFile = extFileInstance.toExtFile();
return new Promise((resolve, reject) => { return new Promise((resolve, reject) => {
...@@ -118,6 +162,7 @@ export const fakeFuiUpload = ( ...@@ -118,6 +162,7 @@ export const fakeFuiUpload = (
const status = true; const status = true;
const message = DropzoneLocalizer.fakeuploadsuccess as string; const message = DropzoneLocalizer.fakeuploadsuccess as string;
const payload = { url: "" }; const payload = { url: "" };
resolve({ resolve({
id: extFile.id, id: extFile.id,
serverResponse: { status, message, payload }, serverResponse: { status, message, payload },
...@@ -147,4 +192,3 @@ export const fakeFuiUpload = ( ...@@ -147,4 +192,3 @@ export const fakeFuiUpload = (
}, 1700); }, 1700);
}); });
}; };
0% Loading or .
You are about to add 0 people to the discussion. Proceed with caution.
Please register or to comment