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

composerContextClipboard.ts

215 lines7.3 KB

1import { requireNativeModule } from "expo";
2import {
3 type ComposerContextClipboardFragment,
4 type ComposerContextRecord,
5 PROVIDER_SEND_TURN_MAX_ATTACHMENTS,
6 PROVIDER_SEND_TURN_MAX_FILE_BYTES,
7 PROVIDER_SEND_TURN_MAX_IMAGE_BYTES,
8 COMPOSER_CONTEXT_MAX_RECORDS,
9 type EnvironmentId,
10} from "@t3tools/contracts";
11import {
12 decodeComposerContextClipboardHtml,
13 decodeComposerContextFragment,
14 encodeComposerContextFragment,
15} from "@t3tools/shared/composerContextClipboard";
16import { threadContextsOutsideEnvironment } from "@t3tools/shared/composerContextReferences";
17import { executeAtomQuery, squashAtomCommandFailure } from "@t3tools/client-runtime/state/runtime";
18import { resolveAssetUrl } from "@t3tools/client-runtime/state/assets";
19import * as Option from "effect/Option";
20import { appAtomRegistry } from "../state/atom-registry";
21import { assetEnvironment } from "../state/assets";
22import { environmentSession } from "../state/session";
23import { downloadAttachmentForPreview } from "./attachmentDownload";
24import {
25 persistComposerAttachmentFile,
26 removePersistedComposerAttachmentFile,
27 type DraftComposerAttachment,
28} from "./composerImages";
29import { referencedComposerContext, reidentifyComposerContext } from "./composerContext";
30import { uuidv4 } from "./uuid";
31import {
32 findLocalComposerClipboardAttachment,
33 waitForComposerDraftsLoaded,
34} from "../state/use-composer-drafts";
35import { loadLocalAttachmentPreview } from "./localAttachmentPreview";
36​
37export interface NativeContextClipboard {
38 readonly text: string;
39 readonly fragment: string;
40 readonly html: string;
42​
43function checkAborted(signal: AbortSignal): void {
44 if (signal.aborted) throw new Error("Context import cancelled");
46​
47const nativeClipboard = () =>
48 requireNativeModule<{
49 writeContextClipboard: (text: string, fragment: string) => Promise<void>;
50 }>("T3ComposerEditor");
51​
52export function writeComposerContextClipboard(
53 text: string,
54 fragment: ComposerContextClipboardFragment,
55): Promise<void> {
56 const encoded = encodeComposerContextFragment(fragment);
57 if (!encoded)
58 return Promise.reject(
59 new Error("This context selection is too large to copy. Select fewer items."),
60 );
61 return nativeClipboard().writeContextClipboard(text, encoded);
63​
64export async function importComposerContextClipboard(
65 input: NativeContextClipboard,
66 existingCount: number,
67 signal: AbortSignal,
68 existingContextCount = 0,
69 destinationEnvironmentId?: EnvironmentId,
70) {
71 const fragment =
72 decodeComposerContextFragment(input.fragment) ?? decodeComposerContextClipboardHtml(input.html);
73 if (!fragment) return null;
74 const selected = referencedComposerContext(input.text, { version: 1, records: fragment.records });
75 const imported = reidentifyComposerContext(input.text, selected?.records ?? [], uuidv4);
76 const skippedThreads =
77 destinationEnvironmentId === undefined
78 ? []
79 : threadContextsOutsideEnvironment({
80 text: imported.text,
81 records: imported.context.records,
82 environmentId: destinationEnvironmentId,
83 });
84 const skippedIds = new Set(skippedThreads.map((record) => record.contextId));
85 const retained = imported.context.records.filter((record) => !skippedIds.has(record.contextId));
86 if (existingContextCount + retained.length > COMPOSER_CONTEXT_MAX_RECORDS)
87 throw new Error("Remove some context items from the draft before pasting more.");
88 const attachments: DraftComposerAttachment[] = [];
89 const records: ComposerContextRecord[] = [];
90 const failures: string[] = [];
91 try {
92 for (const record of retained) {
93 checkAborted(signal);
94 if (!("attachmentId" in record)) {
95 records.push(record);
96 continue;
97 }
98 try {
99 if (existingCount + attachments.length >= PROVIDER_SEND_TURN_MAX_ATTACHMENTS)
100 throw new Error("Attachment limit reached");
101 const file = await importAttachment(record, fragment.source.environmentId, signal);
102 attachments.push(file);
103 records.push({ ...record, attachmentId: file.id });
104 } catch (error) {
105 if (signal.aborted) throw error;
106 failures.push(record.name);
107 }
108 }
109 return {
110 text: imported.text,
111 context: { version: 1 as const, records },
112 attachments,
113 failures,
114 skippedThreads: skippedThreads.map((record) => record.title),
115 };
116 } catch (error) {
117 await Promise.all(
118 attachments.map((attachment) =>
119 attachment.fileUri
120 ? removePersistedComposerAttachmentFile(attachment.fileUri)
121 : Promise.resolve(),
122 ),
123 );
124 throw error;
125 }
127​
128async function importAttachment(
129 record: Extract<ComposerContextRecord, { attachmentId: string }>,
130 environmentId: EnvironmentId,
131 signal: AbortSignal,
132): Promise<DraftComposerAttachment> {
133 await waitForComposerDraftsLoaded();
134 checkAborted(signal);
135 const local = findLocalComposerClipboardAttachment(environmentId, record.attachmentId);
136 if (local) {
137 if (!local.fileUri && local.type === "image" && local.dataUrl)
138 return {
139 ...local,
140 id: uuidv4(),
141 uploadedAttachmentId: undefined,
142 uploadEnvironmentId: undefined,
143 };
144 if (local.fileUri) {
145 const preview = await loadLocalAttachmentPreview(
146 { ...local, fileUri: local.fileUri },
147 signal,
148 );
149 if (!preview) throw new Error("Context import cancelled");
150 try {
151 return await persistImportedAttachment(record, preview.uri, signal);
152 } finally {
153 preview.dispose();
154 }
155 }
156 }
157 const connection = appAtomRegistry.get(
158 environmentSession.preparedConnectionValueAtom(environmentId),
159 );
160 if (Option.isNone(connection)) throw new Error("Reconnect to the source environment");
161 const result = await executeAtomQuery(
162 appAtomRegistry,
163 assetEnvironment.createUrl({
164 environmentId,
165 input: {
166 resource: { _tag: "attachment", attachmentId: record.attachmentId, fileName: record.name },
167 },
168 }),
169 { refresh: true, reportFailure: false },
170 );
171 if (result._tag === "Failure") throw squashAtomCommandFailure(result);
172 checkAborted(signal);
173 const url = resolveAssetUrl(connection.value.httpBaseUrl, result.value.relativeUrl);
174 if (!url) throw new Error("Attachment URL unavailable");
175 const temporary = await downloadAttachmentForPreview({
176 attachment: { name: record.name, mimeType: record.mimeType },
177 url,
178 signal,
179 });
180 if (!temporary) throw new Error("Attachment import cancelled");
181 try {
182 return await persistImportedAttachment(record, temporary.uri, signal);
183 } finally {
184 temporary.dispose();
185 }
187​
188async function persistImportedAttachment(
189 record: Extract<ComposerContextRecord, { attachmentId: string }>,
190 uri: string,
191 signal: AbortSignal,
192): Promise<DraftComposerAttachment> {
193 const fileUri = await persistComposerAttachmentFile(
194 uri,
195 record.name,
196 record.kind === "image"
197 ? PROVIDER_SEND_TURN_MAX_IMAGE_BYTES
198 : PROVIDER_SEND_TURN_MAX_FILE_BYTES,
199 );
200 if (signal.aborted) {
201 await removePersistedComposerAttachmentFile(fileUri);
202 checkAborted(signal);
203 }
204 const { File } = await import("expo-file-system");
205 const common = {
206 id: uuidv4(),
207 fileUri,
208 name: record.name,
209 mimeType: record.mimeType,
210 sizeBytes: new File(fileUri).size,
211 };
212 return record.kind === "image"
213 ? { ...common, type: "image", previewUri: fileUri }
214 : { ...common, type: "file" };