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

questionAttachments.ts

120 lines4.2 KB

1import { scopedThreadKey } from "@t3tools/client-runtime/environment";
2import {
3 onThreadRequestsResolved,
4 resolvedQuestionDraftKeys,
5} from "@t3tools/client-runtime/state/thread-requests";
6import type { EnvironmentId, ScopedThreadRef, ThreadId } from "@t3tools/contracts";
7import { create } from "zustand";
8import { DraftId, useComposerDraftStore } from "./composerDraftStore";
9import { releaseDraftAttachments } from "./lib/attachmentUploadQueue";
10​
11export function questionAttachmentDraftPrefix(
12 environmentId: EnvironmentId,
13 threadId: ThreadId,
14): string {
15 return `${encodeURIComponent(JSON.stringify(environmentId))}:question-${encodeURIComponent(JSON.stringify(threadId))}-`;
17​
18export function questionAttachmentDraftId(
19 environmentId: EnvironmentId,
20 threadId: ThreadId,
21 requestId: string,
22 questionId: string,
23): DraftId {
24 return DraftId.make(
25 `${questionAttachmentDraftPrefix(environmentId, threadId)}${encodeURIComponent(JSON.stringify([requestId, questionId]))}`,
26 );
28​
29type OpenQuestionAttachmentDraft = {
30 readonly draftId: DraftId;
31 readonly requestKeys: ReadonlyArray<DraftId>;
32};
33​
34const openQuestionDrafts = new Map<string, OpenQuestionAttachmentDraft>();
35​
36export function openQuestionAttachmentDraft(
37 threadRef: ScopedThreadRef,
38): OpenQuestionAttachmentDraft | null {
39 return openQuestionDrafts.get(scopedThreadKey(threadRef)) ?? null;
41​
42export function countQuestionRequestAttachments(draftId: DraftId): number | null {
43 for (const draft of openQuestionDrafts.values()) {
44 if (draft.draftId === draftId) return countQuestionAttachments(draft.requestKeys);
45 }
46 return null;
48​
49export function trackOpenQuestionAttachmentDraft(
50 threadRef: ScopedThreadRef,
51 draft: OpenQuestionAttachmentDraft,
52): () => void {
53 const key = scopedThreadKey(threadRef);
54 openQuestionDrafts.set(key, draft);
55 return () => {
56 if (openQuestionDrafts.get(key) === draft) openQuestionDrafts.delete(key);
57 };
59​
60export const useQuestionAttachmentPreparation = create<{ counts: Record<string, number> }>(() => ({
61 counts: {},
62}));
63​
64export function countQuestionAttachments(keys: ReadonlyArray<DraftId>): number {
65 const store = useComposerDraftStore.getState();
66 const { counts } = useQuestionAttachmentPreparation.getState();
67 return keys.reduce((total, key) => {
68 const draft = store.getComposerDraft(key);
69 return total + (draft?.images.length ?? 0) + (draft?.files.length ?? 0) + (counts[key] ?? 0);
70 }, 0);
72​
73export function changeQuestionAttachmentPreparation(key: DraftId, delta: number): void {
74 useQuestionAttachmentPreparation.setState((state) =>
75 delta < 0 && !(key in state.counts)
76 ? state
77 : {
78 counts: { ...state.counts, [key]: Math.max(0, (state.counts[key] ?? 0) + delta) },
79 },
80 );
82​
83export function clearQuestionAttachmentDraft(key: DraftId): void {
84 const store = useComposerDraftStore.getState();
85 const draft = store.getComposerDraft(key);
86 if (draft) {
87 releaseDraftAttachments([...draft.images, ...draft.files]);
88 for (const image of draft.images) {
89 if (image.previewUrl.startsWith("blob:")) URL.revokeObjectURL(image.previewUrl);
90 }
91 }
92 store.clearComposerContent(key);
93 useQuestionAttachmentPreparation.setState(({ counts }) => {
94 const next = { ...counts };
95 delete next[key];
96 return { counts: next };
97 });
99​
100/** Clears the thread's question attachment drafts for every request outside `pendingRequestIds`. */
101function pruneResolvedQuestionAttachmentDrafts(
102 environmentId: EnvironmentId,
103 threadId: ThreadId,
104 pendingRequestIds: ReadonlyArray<string>,
105): void {
106 const keys = new Set([
107 ...Object.keys(useComposerDraftStore.getState().draftsByThreadKey),
108 ...Object.keys(useQuestionAttachmentPreparation.getState().counts),
109 ]);
110 const prefix = questionAttachmentDraftPrefix(environmentId, threadId);
111 for (const key of resolvedQuestionDraftKeys(keys, prefix, pendingRequestIds)) {
112 clearQuestionAttachmentDraft(DraftId.make(key));
113 }
115​
116// Attachment drafts persist across reloads, so a request resolved while this
117// client was away is pruned when its thread's projection first synchronizes.
118onThreadRequestsResolved(({ environmentId, threadId, pendingRequestIds }) =>
119 pruneResolvedQuestionAttachmentDrafts(environmentId, threadId, pendingRequestIds),
120);