54 lines
1.8 KiB
TypeScript
54 lines
1.8 KiB
TypeScript
import type { ApprovalRequestId, EnvironmentId, ThreadId } from "@t3tools/contracts";
|
|
import { create } from "zustand";
|
|
import { DraftId, useComposerDraftStore } from "./composerDraftStore";
|
|
import { releaseDraftAttachments } from "./lib/attachmentUploadQueue";
|
|
|
|
export function questionAttachmentDraftPrefix(
|
|
environmentId: EnvironmentId,
|
|
threadId: ThreadId,
|
|
): string {
|
|
return `${encodeURIComponent(JSON.stringify(environmentId))}:question-${encodeURIComponent(JSON.stringify(threadId))}-`;
|
|
}
|
|
|
|
export function questionAttachmentDraftId(
|
|
environmentId: EnvironmentId,
|
|
threadId: ThreadId,
|
|
requestId: ApprovalRequestId,
|
|
questionId: string,
|
|
): DraftId {
|
|
return DraftId.make(
|
|
`${questionAttachmentDraftPrefix(environmentId, threadId)}${encodeURIComponent(JSON.stringify([requestId, questionId]))}`,
|
|
);
|
|
}
|
|
|
|
export const useQuestionAttachmentPreparation = create<{ counts: Record<string, number> }>(() => ({
|
|
counts: {},
|
|
}));
|
|
|
|
export function changeQuestionAttachmentPreparation(key: DraftId, delta: number): void {
|
|
useQuestionAttachmentPreparation.setState((state) =>
|
|
delta < 0 && !(key in state.counts)
|
|
? state
|
|
: {
|
|
counts: { ...state.counts, [key]: Math.max(0, (state.counts[key] ?? 0) + delta) },
|
|
},
|
|
);
|
|
}
|
|
|
|
export function clearQuestionAttachmentDraft(key: DraftId): void {
|
|
const store = useComposerDraftStore.getState();
|
|
const draft = store.getComposerDraft(key);
|
|
if (draft) {
|
|
releaseDraftAttachments([...draft.images, ...draft.files]);
|
|
for (const image of draft.images) {
|
|
if (image.previewUrl.startsWith("blob:")) URL.revokeObjectURL(image.previewUrl);
|
|
}
|
|
}
|
|
store.clearComposerContent(key);
|
|
useQuestionAttachmentPreparation.setState(({ counts }) => {
|
|
const next = { ...counts };
|
|
delete next[key];
|
|
return { counts: next };
|
|
});
|
|
}
|