Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Fixes issues with the attachments preview. #1239

Merged
merged 2 commits into from
Oct 11, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
33 changes: 20 additions & 13 deletions src/hooks/useFileUploader.js
Original file line number Diff line number Diff line change
@@ -1,4 +1,7 @@
// eslint-disable-next-line @bigbinary/neeto/no-axios-import-outside-apis, @bigbinary/neeto/use-snake-case-for-api-connector-filename
// eslint-disable-next-line @bigbinary/neeto/use-snake-case-for-api-connector-filename
import { useRef } from "react";

// eslint-disable-next-line @bigbinary/neeto/no-axios-import-outside-apis,
import axios from "axios";
import { noop, hyphenate, isNot, isNotPresent } from "neetocist";
import { Toastr } from "neetoui";
Expand All @@ -9,6 +12,7 @@ import useFileUploadStore from "src/stores/useFileUploadStore";
import DirectUpload from "utils/DirectUpload";

import { FILE_UPLOAD_STATUS } from "./constants/fileUploader";
import { getRandomString } from "./utils";
import { selectFiles } from "./utils/fileUploader";

let uploadControllers = {};
Expand All @@ -18,26 +22,27 @@ const useFileUploader = ({
attachments: previousAttachments = [],
setIsUploadingOnHost = noop,
}) => {
const contextIdRef = useRef(getRandomString());
const { t } = useTranslation();

const { current: contextId } = contextIdRef;
const {
addFiles: addFilesToStore,
isUploading,
getNextQueuedFile,
updateFileStatus,
removeFilesFromQueue,
setIsUploading,
updateFileUploadProgress,
files,
removeFile,
} = useFileUploadStore.pick();
const { files = [], isUploading } = useFileUploadStore.pick([contextId]);

const handleUploadProgress = (xhr, file) => {
if (!xhr.event.lengthComputable) return;
const bytesUploaded = xhr.loaded;
const bytesTotal = xhr.total;
const progress = Math.round((bytesUploaded / bytesTotal) * 100);
updateFileUploadProgress(file.id, progress);
updateFileUploadProgress(contextId, file.id, progress);
};

const uploadFile = async file => {
Expand All @@ -51,7 +56,7 @@ const useFileUploader = ({

try {
const { data = {}, ...response } = await upload.create();
updateFileStatus(file.id, FILE_UPLOAD_STATUS.UPLOADED);
updateFileStatus(contextId, file.id, FILE_UPLOAD_STATUS.UPLOADED);

return {
id: file.id,
Expand All @@ -66,38 +71,39 @@ const useFileUploader = ({
}
// eslint-disable-next-line no-console
console.error("Failed to upload attachment", error);
removeFile(file.id);
removeFile(contextId, file.id);

return null;
}
};

const handleUploadFiles = async () => {
const queuedFile = getNextQueuedFile();
const queuedFile = getNextQueuedFile(contextId);

if (isNotPresent(queuedFile)) {
setIsUploading(false);
setIsUploading(contextId, false);
setIsUploadingOnHost(false);

return [];
}

updateFileStatus(queuedFile.id, FILE_UPLOAD_STATUS.UPLOADING);
updateFileStatus(contextId, queuedFile.id, FILE_UPLOAD_STATUS.UPLOADING);

const [uploadedFile, remainingUploadedFiles] = await Promise.all([
uploadFile(queuedFile),
handleUploadFiles(),
]);

const uploadedFiles = [uploadedFile, ...remainingUploadedFiles];
const uploadedFileIds = pluck("id", uploadedFiles);
removeFilesFromQueue(uploadedFileIds);
removeFilesFromQueue(contextId, uploadedFileIds);
uploadControllers = omit(uploadedFileIds, uploadControllers);

return uploadedFiles.filter(isNot(null));
};

const uploadFiles = () => {
setIsUploading(true);
setIsUploading(contextId, true);
setIsUploadingOnHost(true);

return handleUploadFiles();
Expand All @@ -117,12 +123,13 @@ const useFileUploader = ({
type: file.type,
status: FILE_UPLOAD_STATUS.QUEUED,
}));
addFilesToStore(selectedFiles);

addFilesToStore(contextId, selectedFiles);
};

const cancelUpload = fileId => {
uploadControllers[fileId]?.abort?.();
removeFile(fileId);
removeFile(contextId, fileId);
};

return {
Expand Down
2 changes: 2 additions & 0 deletions src/hooks/utils/index.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,2 @@
export const getRandomString = () =>
Math.random().toString(36).substring(7).toUpperCase();
69 changes: 49 additions & 20 deletions src/stores/useFileUploadStore.js
Original file line number Diff line number Diff line change
Expand Up @@ -5,41 +5,70 @@ import { create } from "zustand";
/** @type {import("neetocommons/react-utils").ZustandStoreHook} */
const useFileUploadStore = create(
withImmutableActions((set, get) => ({
files: [],
isUploading: false,
// {[contextId]: { files: File[], isUploading: boolean }}

addFiles: newFiles =>
set(state => ({ files: [...state.files, ...newFiles] })),
addFiles: (contextId, newFiles) =>
set(state => ({
[contextId]: {
...state[contextId],
files: [...(state[contextId]?.["files"] || []), ...newFiles],
},
})),

updateFileStatus: (fileId, status) =>
updateFileStatus: (contextId, fileId, status) =>
set(state => ({
files: state.files.map(file =>
file.id === fileId ? { ...file, status } : file
),
[contextId]: {
...state[contextId],
files: state[contextId]?.["files"]?.map(file =>
file.id === fileId ? { ...file, status } : file
),
},
})),

updateFileUploadProgress: (fileId, progress) =>
updateFileUploadProgress: (contextId, fileId, progress) =>
set(state => ({
files: state.files.map(file =>
file.id === fileId ? { ...file, progress } : file
),
[contextId]: {
...state[contextId],
files:
state[contextId]?.["files"]?.map(file =>
file.id === fileId ? { ...file, progress } : file
) || [],
},
})),

removeFile: fileId =>
set(state => ({ files: removeById(fileId, state.files) })),
removeFile: (contextId, fileId) =>
set(state => ({
[contextId]: {
...state[contextId],
files: removeById(fileId, state[contextId]?.["files"] || []),
},
})),

setIsUploading: status => set({ isUploading: status }),
setIsUploading: (contextId, status) =>
set(state => ({
[contextId]: {
...(state[contextId] ?? []),
isUploading: status,
},
})),

getNextQueuedFile: () => {
const { files } = get();
getNextQueuedFile: contextId => {
const { files } = get()[contextId];

return findBy(({ status }) => status === "queued", files);
},

removeFilesFromQueue: uploadedFiles => {
const { files } = get();
removeFilesFromQueue: (contextId, uploadedFiles) => {
const data = get()[contextId];

set({ files: files.filter(({ id }) => !uploadedFiles.includes(id)) });
set({
[contextId]: {
...data,
files: (data["files"] || []).filter(
({ id }) => !uploadedFiles.includes(id)
),
},
});
},
}))
);
Expand Down
Loading