Open History to see the last commit
1import type { 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))}-`;
11}
12
13export function questionAttachmentDraftId(
14 environmentId: EnvironmentId,
15 threadId: ThreadId,
16 requestId: string,
17 questionId: string,
18): DraftId {
19 return DraftId.make(
20 `${questionAttachmentDraftPrefix(environmentId, threadId)}${encodeURIComponent(JSON.stringify([requestId, questionId]))}`,
21 );
22}
23
24export const useQuestionAttachmentPreparation = create<{ counts: Record<string, number> }>(() => ({
25 counts: {},
26}));
27
28export function countQuestionAttachments(keys: ReadonlyArray<DraftId>): number {
29 const store = useComposerDraftStore.getState();
30 const { counts } = useQuestionAttachmentPreparation.getState();
31 return keys.reduce((total, key) => {
32 const draft = store.getComposerDraft(key);
33 return total + (draft?.images.length ?? 0) + (draft?.files.length ?? 0) + (counts[key] ?? 0);
34 }, 0);
35}
36
37export function changeQuestionAttachmentPreparation(key: DraftId, delta: number): void {
38 useQuestionAttachmentPreparation.setState((state) =>
39 delta < 0 && !(key in state.counts)
40 ? state
41 : {
42 counts: { ...state.counts, [key]: Math.max(0, (state.counts[key] ?? 0) + delta) },
43 },
44 );
45}
46
47export function clearQuestionAttachmentDraft(key: DraftId): void {
48 const store = useComposerDraftStore.getState();
49 const draft = store.getComposerDraft(key);
50 if (draft) {
51 releaseDraftAttachments([...draft.images, ...draft.files]);
52 for (const image of draft.images) {
53 if (image.previewUrl.startsWith("blob:")) URL.revokeObjectURL(image.previewUrl);
54 }
55 }
56 store.clearComposerContent(key);
57 useQuestionAttachmentPreparation.setState(({ counts }) => {
58 const next = { ...counts };
59 delete next[key];
60 return { counts: next };
61 });
62}