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

composerContextClipboard.ts

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