@wordpress/media-utils
Version:
WordPress Media Upload Utils.
103 lines (102 loc) • 3.08 kB
JavaScript
// packages/media-utils/src/components/media-upload-modal/use-upload-status.ts
import { useState, useCallback } from "@wordpress/element";
import { isBlobURL } from "@wordpress/blob";
import { UploadError } from "../../utils/upload-error.mjs";
var idCounter = 0;
var batchIdCounter = 0;
function useUploadStatus({
onBatchComplete
} = {}) {
const [uploadingFiles, setUploadingFiles] = useState(
[]
);
const clearCompleted = useCallback(() => {
setUploadingFiles(
(prev) => prev.filter((item) => item.status !== "uploaded")
);
}, []);
const dismissError = useCallback((fileId) => {
setUploadingFiles(
(prev) => prev.filter((item) => item.id !== fileId)
);
}, []);
const registerBatch = useCallback(
(files) => {
const batchId = String(++batchIdCounter);
const batchSize = files.length;
const newEntries = files.map((file) => ({
id: String(++idCounter),
batchId,
name: file.name,
status: "uploading"
}));
setUploadingFiles((prev) => [...prev, ...newEntries]);
let successCount = 0;
let errorCount = 0;
let batchDone = false;
let successAttachments = [];
const completeBatchIfDone = () => {
if (batchDone || successCount + errorCount < batchSize) {
return;
}
batchDone = true;
setUploadingFiles(
(prev) => prev.map(
(item) => item.batchId === batchId && item.status === "uploading" ? {
...item,
status: "uploaded"
} : item
)
);
onBatchComplete?.(successAttachments);
};
const onFileChange = (attachments) => {
if (batchDone) {
return;
}
const allReal = attachments.every(
(attachment) => attachment.id && attachment.url && !isBlobURL(attachment.url)
);
if (!allReal) {
return;
}
successCount = attachments.length;
successAttachments = attachments;
completeBatchIfDone();
};
const onError = (error) => {
const fileName = error instanceof UploadError ? error.file.name : void 0;
setUploadingFiles((prev) => {
let matched = false;
return prev.map((item) => {
if (!matched && item.batchId === batchId && item.status === "uploading" && (!fileName || item.name === fileName)) {
matched = true;
return {
...item,
status: "error",
error: error.message
};
}
return item;
});
});
errorCount++;
completeBatchIfDone();
};
return { onFileChange, onError };
},
[onBatchComplete]
);
const allComplete = uploadingFiles.length > 0 && uploadingFiles.every((item) => item.status !== "uploading");
return {
uploadingFiles,
registerBatch,
dismissError,
clearCompleted,
allComplete
};
}
export {
useUploadStatus
};
//# sourceMappingURL=use-upload-status.mjs.map