Open History to see the last commit
1import type {
2 ChatAttachment,
3 ComposerContextId,
4 EnvironmentContextRecord,
5 PreviewAnnotationPayload,
6 ThreadContextRecord,
7} from "@t3tools/contracts";
8import { useEffect, useState } from "react";
9
10import type { ComposerFileAttachment, ComposerImageAttachment } from "../../composerDraftStore";
11import { fileContextReference, previewAnnotationContextId } from "../../lib/composerContextRecords";
12import type { TerminalContextDraft } from "../../lib/terminalContext";
13import type { ReviewCommentContext } from "../../reviewCommentContext";
14import { isQueuedFileAttachment, isQueuedImageAttachment } from "./queuedMessageEdit";
15
16interface RetainedPreviewAnnotation {
17 annotation: PreviewAnnotationPayload;
18 image: ComposerImageAttachment | undefined;
19}
20
21export interface QueuedAttachmentContextBinding {
22 readonly attachment: ChatAttachment;
23 readonly contextIds: ReadonlyArray<ComposerContextId>;
24}
25
26export interface RetainedAttachmentContextPayloads {
27 files: Map<string, ComposerFileAttachment>;
28 previewAnnotations: Map<string, RetainedPreviewAnnotation>;
29 /** Queued images brought back because their chip reappeared. */
30 restoredQueuedImageIds: Set<string>;
31}
32
33export interface RetainedContextPayloads extends RetainedAttachmentContextPayloads {
34 terminals: Map<string, TerminalContextDraft>;
35 reviewComments: Map<string, ReviewCommentContext>;
36 threads: Map<string, ThreadContextRecord>;
37 environments: Map<string, EnvironmentContextRecord>;
38}
39
40function createRetainedContextPayloads(): RetainedContextPayloads {
41 return {
42 terminals: new Map(),
43 reviewComments: new Map(),
44 threads: new Map(),
45 environments: new Map(),
46 files: new Map(),
47 previewAnnotations: new Map(),
48 restoredQueuedImageIds: new Set(),
49 };
50}
51
52// Deleted chips keep their payloads until their draft's undo history ends.
53export function useRetainedContextPayloads(draftTargetKey: string): RetainedContextPayloads {
54 const [draft, setDraft] = useState(() => ({
55 targetKey: draftTargetKey,
56 payloads: createRetainedContextPayloads(),
57 }));
58 if (draft.targetKey !== draftTargetKey) {
59 setDraft({ targetKey: draftTargetKey, payloads: createRetainedContextPayloads() });
60 }
61 const retained = draft.payloads;
62 // oxlint-disable-next-line t3code/no-unreasoned-state-sync -- clears the retained payload maps when the draft target changes or the composer unmounts
63 useEffect(
64 () => () => {
65 for (const payloads of Object.values(retained)) payloads.clear();
66 },
67 [retained],
68 );
69 return retained;
70}
71
72export function reconcileAttachmentContextReferences(input: {
73 referencedContextIds: ReadonlySet<string>;
74 files: ReadonlyArray<ComposerFileAttachment>;
75 /** Attachments of a queued message being edited, and those removed during the edit. */
76 queuedAttachments?: ReadonlyArray<QueuedAttachmentContextBinding>;
77 removedQueuedAttachments?: ReadonlyArray<QueuedAttachmentContextBinding>;
78 /** The change came from undo or redo. */
79 fromHistory?: boolean;
80 images: ReadonlyArray<ComposerImageAttachment>;
81 previewAnnotations: ReadonlyArray<PreviewAnnotationPayload>;
82 retained: RetainedAttachmentContextPayloads;
83}): {
84 filesToRemove: string[];
85 filesToRestore: ComposerFileAttachment[];
86 queuedAttachmentIdsToRemove: string[];
87 queuedAttachmentsToRestore: ChatAttachment[];
88 annotationIdsToRemove: string[];
89 annotationsToRestore: RetainedPreviewAnnotation[];
90} {
91 const liveFileContextIds = new Set<string>(
92 input.files.map((file) => fileContextReference(file).contextId),
93 );
94 const filesToRemove: string[] = [];
95 for (const file of input.files) {
96 const contextId = fileContextReference(file).contextId;
97 if (input.referencedContextIds.has(contextId)) continue;
98 input.retained.files.set(contextId, file);
99 filesToRemove.push(file.id);
100 }
101 const filesToRestore = [...input.referencedContextIds].flatMap((contextId) => {
102 if (liveFileContextIds.has(contextId)) return [];
103 const file = input.retained.files.get(contextId);
104 return file ? [file] : [];
105 });
106
107 const isReferenced = (entry: QueuedAttachmentContextBinding) =>
108 entry.contextIds.some((contextId) => input.referencedContextIds.has(contextId));
109 const restoredImageIds = input.retained.restoredQueuedImageIds;
110 const queuedAttachmentIdsToRemove = (input.queuedAttachments ?? []).flatMap((entry) => {
111 if (entry.contextIds.length === 0 || isReferenced(entry)) return [];
112 if (isQueuedFileAttachment(entry.attachment)) return [entry.attachment.id];
113 // Like draft images, a queued image outlives its deleted chip, unless undo or redo
114 // takes away a chip whose return had brought the image back.
115 const wasRestored = restoredImageIds.delete(entry.attachment.id);
116 return wasRestored && input.fromHistory ? [entry.attachment.id] : [];
117 });
118 const queuedAttachmentsToRestore = (input.removedQueuedAttachments ?? []).flatMap((entry) => {
119 if (!isReferenced(entry)) return [];
120 if (isQueuedImageAttachment(entry.attachment)) restoredImageIds.add(entry.attachment.id);
121 return [entry.attachment];
122 });
123
124 const imagesById = new Map(input.images.map((image) => [image.id, image]));
125 const liveAnnotationContextIds = new Set<string>(
126 input.previewAnnotations.map((annotation) => previewAnnotationContextId(annotation.id)),
127 );
128 const annotationIdsToRemove: string[] = [];
129 for (const annotation of input.previewAnnotations) {
130 const contextId = previewAnnotationContextId(annotation.id);
131 if (input.referencedContextIds.has(contextId)) continue;
132 input.retained.previewAnnotations.set(contextId, {
133 annotation,
134 image: imagesById.get(annotation.id),
135 });
136 annotationIdsToRemove.push(annotation.id);
137 }
138 const annotationsToRestore = [...input.referencedContextIds].flatMap((contextId) => {
139 if (liveAnnotationContextIds.has(contextId)) return [];
140 const retained = input.retained.previewAnnotations.get(contextId);
141 return retained ? [retained] : [];
142 });
143
144 return {
145 filesToRemove,
146 filesToRestore,
147 queuedAttachmentIdsToRemove,
148 queuedAttachmentsToRestore,
149 annotationIdsToRemove,
150 annotationsToRestore,
151 };
152}