Skip to content
Source
Sign inSign up
pingdotgg/t3code
Open History to see the last commit

attachmentUploadState.ts

54 lines1.7 KB

1import type { EnvironmentId } from "@t3tools/contracts";
2​
3export type ReadyAttachmentUpload = {
4 readonly status: "ready";
5 readonly environmentId: EnvironmentId;
6 readonly attachmentId: string;
7};
8​
9export type AttachmentUploadState =
10 | {
11 readonly status: "uploading";
12 readonly environmentId: EnvironmentId;
13 readonly progress: number;
14 readonly previous?: ReadyAttachmentUpload;
15 }
16 | ReadyAttachmentUpload
17 | {
18 readonly status: "failed";
19 readonly environmentId: EnvironmentId;
20 readonly reason: string;
21 readonly attachmentId?: string;
22 readonly previous?: ReadyAttachmentUpload;
23 };
24​
25export function attachmentUploadBlockReason(input: {
26 readonly imageIds: ReadonlyArray<string>;
27 readonly uploadsByImageId: Readonly<Record<string, AttachmentUploadState>>;
28 readonly environmentId: EnvironmentId;
29}): string | null {
30 let pending = 0;
31 let failed = 0;
32​
33 for (const imageId of input.imageIds) {
34 const upload = input.uploadsByImageId[imageId];
35 if (upload?.status === "failed" && upload.environmentId === input.environmentId) {
36 failed += 1;
37 } else if (upload?.status !== "ready" || upload.environmentId !== input.environmentId) {
38 pending += 1;
39 }
40 }
41​
42 if (failed > 0) {
43 return failed === 1 ? "Retry or remove the failed image" : "Retry or remove the failed images";
44 }
45 if (pending > 0) {
46 return pending === 1 ? "Image still uploading" : "Images still uploading";
47 }
48 return null;
50​
51export function formatAttachmentUploadProgress(progress: number): string {
52 const bounded = Math.max(0, Math.min(1, Number.isFinite(progress) ? progress : 0));
53 return `${Math.floor(bounded * 100)}%`;