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

questionAttachments.ts

53 lines1.8 KB

1import type { ApprovalRequestId, EnvironmentId, ThreadId } from "@t3tools/contracts";
2import { create } from "zustand";
3import { DraftId, useComposerDraftStore } from "./composerDraftStore";
4import { releaseDraftAttachments } from "./lib/attachmentUploadQueue";
5​
6export function questionAttachmentDraftPrefix(
7 environmentId: EnvironmentId,
8 threadId: ThreadId,
9): string {
10 return `${encodeURIComponent(JSON.stringify(environmentId))}:question-${encodeURIComponent(JSON.stringify(threadId))}-`;
12​
13export function questionAttachmentDraftId(
14 environmentId: EnvironmentId,
15 threadId: ThreadId,
16 requestId: ApprovalRequestId,
17 questionId: string,
18): DraftId {
19 return DraftId.make(
20 `${questionAttachmentDraftPrefix(environmentId, threadId)}${encodeURIComponent(JSON.stringify([requestId, questionId]))}`,
21 );
23​
24export const useQuestionAttachmentPreparation = create<{ counts: Record<string, number> }>(() => ({
25 counts: {},
26}));
27​
28export function changeQuestionAttachmentPreparation(key: DraftId, delta: number): void {
29 useQuestionAttachmentPreparation.setState((state) =>
30 delta < 0 && !(key in state.counts)
31 ? state
32 : {
33 counts: { ...state.counts, [key]: Math.max(0, (state.counts[key] ?? 0) + delta) },
34 },
35 );
37​
38export function clearQuestionAttachmentDraft(key: DraftId): void {
39 const store = useComposerDraftStore.getState();
40 const draft = store.getComposerDraft(key);
41 if (draft) {
42 releaseDraftAttachments([...draft.images, ...draft.files]);
43 for (const image of draft.images) {
44 if (image.previewUrl.startsWith("blob:")) URL.revokeObjectURL(image.previewUrl);
45 }
46 }
47 store.clearComposerContent(key);
48 useQuestionAttachmentPreparation.setState(({ counts }) => {
49 const next = { ...counts };
50 delete next[key];
51 return { counts: next };
52 });