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

attachmentUploadState.ts

68 lines2.2 KB

1import { wholeUploadPercent } from "@t3tools/client-runtime/upload-progress";
2import type { EnvironmentId } from "@t3tools/contracts";
3import { msg, type Msg } from "gt-react";
4​
5import { m, type MessageResolver } from "../i18n/messages";
6​
7export type ReadyAttachmentUpload = {
8 readonly status: "ready";
9 readonly environmentId: EnvironmentId;
10 readonly attachmentId: string;
11};
12​
13export type AttachmentUploadState =
14 | {
15 readonly status: "uploading";
16 readonly environmentId: EnvironmentId;
17 readonly progress: number;
18 readonly previous?: ReadyAttachmentUpload;
19 }
20 | ReadyAttachmentUpload
21 | {
22 readonly status: "failed";
23 readonly environmentId: EnvironmentId;
24 readonly reason: string;
25 /** `reason` as a `msg()`, so the composer shows it in the current language. */
26 readonly reasonMessage?: string | Msg;
27 /** Retry/release deletes this id; never use a persisted draft attachment id. */
28 readonly attachmentId?: string;
29 readonly previous?: ReadyAttachmentUpload;
30 };
31​
32export function attachmentUploadFailureText(
33 upload: Extract<AttachmentUploadState, { status: "failed" }>,
34 resolve: MessageResolver,
35): string {
36 return upload.reasonMessage === undefined ? upload.reason : resolve(upload.reasonMessage);
38​
39export function attachmentUploadBlockReason(
40 input: {
41 readonly imageIds: ReadonlyArray<string>;
42 readonly uploadsByImageId: Readonly<Record<string, AttachmentUploadState>>;
43 readonly environmentId: EnvironmentId;
44 },
45 resolve: MessageResolver = m,
46): string | null {
47 let pending = 0;
48​
49 for (const imageId of input.imageIds) {
50 const upload = input.uploadsByImageId[imageId];
51 // Send retries failed uploads, so they must not disable it.
52 if (upload?.status === "failed" && upload.environmentId === input.environmentId) continue;
53 if (upload?.status !== "ready" || upload.environmentId !== input.environmentId) {
54 pending += 1;
55 }
56 }
57​
58 if (pending > 0) {
59 return pending === 1
60 ? resolve(msg("Attachment still uploading"))
61 : resolve(msg("Attachments still uploading"));
62 }
63 return null;
65​
66export function formatAttachmentUploadProgress(progress: number): string {
67 return `${wholeUploadPercent(progress)}%`;