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

ComposerEditor.tsx

249 lines9.0 KB

1import { ComposerContextId } from "@t3tools/contracts";
2import { useEffect, useMemo, useRef, useState } from "react";
3import { Alert } from "react-native";
4import type { EnvironmentId } from "@t3tools/contracts";
5import { encodeComposerContextFragment } from "@t3tools/shared/composerContextClipboard";
6import { collectComposerContextReferences } from "@t3tools/shared/composerContextReferences";
7import { ComposerEditor as NativeComposerEditor } from "../native/T3ComposerEditor";
8import type { ComposerEditorProps as NativeComposerEditorProps } from "../native/T3ComposerEditor";
9import {
10 appendComposerDraftAttachments,
11 createComposerDraftContextHistory,
12 getComposerDraftAfterSelection,
13 getComposerDraftSnapshot,
14 insertComposerDraftContext,
15 insertComposerDraftText,
16 rememberComposerDraftSelection,
17 setComposerDraftContext,
18 setComposerContextImporting,
19 useComposerDraft,
20} from "../state/use-composer-drafts";
21import { importComposerContextClipboard } from "../lib/composerContextClipboard";
22import { ComposerContextSheet } from "./ComposerContextSheet";
23import { AppText as Text } from "./AppText";
24import {
25 composerDocumentAttachment,
26 composerMentionPath,
27 type ComposerDocumentAttachment,
28} from "../lib/composerContext";
29​
30export type ComposerEditorProps = NativeComposerEditorProps & {
31 readonly draftKey?: string | null;
32 readonly environmentId?: EnvironmentId;
33 readonly onOpenMention?: (path: string) => void;
34 /** Documents open in the file screen; pictures, video and PDF keep their native viewers. */
35 readonly onOpenAttachment?: (attachment: ComposerDocumentAttachment) => void;
36 /**
37 * A resting composer is a target to type in, not a document to navigate. Its chips go inert
38 * so a draft full of them can still be tapped anywhere to start writing; the caller focuses
39 * the editor instead. Chips become live again once the composer is open.
40 */
41 readonly chipsInert?: boolean;
42 /** Called instead of opening a chip while `chipsInert` is set. */
43 readonly onInertChipPress?: () => void;
44};
45​
46export function ComposerEditor({
47 draftKey,
48 environmentId,
49 onOpenMention,
50 onOpenAttachment,
51 chipsInert,
52 onInertChipPress,
53 ...props
54}: ComposerEditorProps) {
55 const draft = useComposerDraft(draftKey ?? null);
56 const contextHistory = useMemo(() => createComposerDraftContextHistory(), [draftKey]);
57 useEffect(() => () => contextHistory.dispose(), [contextHistory]);
58 const changeText = (text: string) => {
59 const restored = contextHistory.restore(
60 text,
61 draftKey ? getComposerDraftSnapshot(draftKey) : draft,
62 );
63 props.onChangeText(text);
64 if (draftKey) {
65 setComposerDraftContext(draftKey, restored.context);
66 appendComposerDraftAttachments(draftKey, restored.attachments, { allowOverflow: true });
67 }
68 };
69 const [selected, setSelected] = useState<{ source: string; start: number; end: number } | null>(
70 null,
71 );
72 const importRef = useRef<AbortController | null>(null);
73 const [importing, setImporting] = useState(false);
74 useEffect(
75 () => () => {
76 importRef.current?.abort();
77 },
78 [draftKey],
79 );
80 const pasteContext = async (
81 clipboard: Parameters<NonNullable<NativeComposerEditorProps["onPasteContext"]>>[0],
82 ) => {
83 if (!draftKey || importRef.current || props.readOnly || props.editable === false) return;
84 const insertion = { text: clipboard.value, ...clipboard.selection };
85 const controller = new AbortController();
86 importRef.current = controller;
87 setImporting(true);
88 setComposerContextImporting(draftKey, true);
89 try {
90 const retained = getComposerDraftAfterSelection(draftKey, insertion);
91 const result = await importComposerContextClipboard(
92 clipboard,
93 retained.attachments.length,
94 controller.signal,
95 retained.context?.records.length ?? 0,
96 );
97 if (!result) {
98 insertComposerDraftText(draftKey, clipboard.text, insertion);
99 return;
100 }
101 if (!insertComposerDraftContext(draftKey, result, insertion)) {
102 Alert.alert(
103 "Could not paste context",
104 "Remove some attachments or context items from the draft, then paste again.",
105 );
106 return;
107 }
108 if (result.failures.length > 0)
109 Alert.alert(
110 "Some attachments could not be copied",
111 "Reconnect to the source environment and copy them again. References without their files are marked unavailable.",
112 );
113 } catch (error) {
114 if (!controller.signal.aborted)
115 Alert.alert(
116 "Could not paste context",
117 error instanceof Error ? error.message : "Try copying again.",
118 );
119 } finally {
120 setComposerContextImporting(draftKey, false);
121 importRef.current = null;
122 setImporting(false);
123 }
124 };
125 const clipboardFragment = useMemo(
126 () =>
127 environmentId && draft.context
128 ? encodeComposerContextFragment({
129 version: 1,
130 source: { environmentId },
131 records: draft.context.records.map((record) => {
132 if (!("attachmentId" in record)) return record;
133 const attachment = draft.attachments.find(
134 (entry) => entry.id === record.attachmentId,
135 );
136 return {
137 ...record,
138 attachmentId:
139 attachment?.uploadEnvironmentId === environmentId
140 ? (attachment.uploadedAttachmentId ?? record.attachmentId)
141 : record.attachmentId,
142 };
143 }),
144 })
145 : "",
146 [environmentId, draft.context, draft.attachments],
147 );
148 const selectedReference = selected
149 ? collectComposerContextReferences(selected.source)[0]
150 : undefined;
151 const selectedSkill = selected?.source.startsWith("$")
152 ? props.skills?.find((skill) => skill.name === selected.source.slice(1))
153 : undefined;
154 const record = draft.context?.records.find(
155 (entry) => entry.contextId === selectedReference?.contextId,
156 );
157 return (
158 <>
159 <NativeComposerEditor
160 {...props}
161 onChangeText={changeText}
162 readOnly={props.readOnly || importing}
163 onSubmit={importing ? undefined : props.onSubmit}
164 clipboardFragment={clipboardFragment ?? undefined}
165 onPasteContext={(clipboard) => void pasteContext(clipboard)}
166 context={draft.context}
167 onContextPress={(selection) => {
168 if (chipsInert) {
169 onInertChipPress?.();
170 return;
171 }
172 const path = composerMentionPath(selection.source, draft.context);
173 if (path && onOpenMention) {
174 onOpenMention(path);
175 return;
176 }
177 const document = composerDocumentAttachment(selection.source, draft.context);
178 if (document && onOpenAttachment) {
179 onOpenAttachment(document);
180 return;
181 }
182 setSelected(selection);
183 }}
184 onSelectionChange={(selection) => {
185 if (draftKey)
186 rememberComposerDraftSelection(
187 draftKey,
188 getComposerDraftSnapshot(draftKey).text,
189 selection,
190 );
191 props.onSelectionChange?.(selection);
192 }}
193 />
194 {importing ? (
195 <Text className="py-2 text-xs text-foreground-muted">Copying context…</Text>
196 ) : null}
197 {selected && (selectedReference || selectedSkill) ? (
198 <ComposerContextSheet
199 label={
200 selectedReference?.label ?? selectedSkill?.displayName ?? selectedSkill?.name ?? "Skill"
201 }
202 record={
203 record ??
204 (selectedSkill
205 ? {
206 version: 1,
207 kind: "skill",
208 contextId: ComposerContextId.make("skill-preview"),
209 label: selectedSkill.name,
210 name: selectedSkill.name,
211 }
212 : undefined)
213 }
214 {...(selectedSkill?.description ? { skillDescription: selectedSkill.description } : {})}
215 {...(selectedSkill?.path && onOpenMention
216 ? {
217 onOpenSkill: () => {
218 setSelected(null);
219 onOpenMention(selectedSkill.path!);
220 },
221 }
222 : {})}
223 environmentId={environmentId}
224 records={draft.context?.records}
225 attachments={draft.attachments}
226 onClose={() => setSelected(null)}
227 onRemove={
228 props.readOnly || props.editable === false
229 ? undefined
230 : () => {
231 if (props.value.slice(selected.start, selected.end) === selected.source) {
232 changeText(
233 props.value.slice(0, selected.start) + props.value.slice(selected.end),
234 );
235 props.onSelectionChange?.({ start: selected.start, end: selected.start });
236 }
237 setSelected(null);
238 }
239 }
240 />
241 ) : null}
242 </>
243 );
245export type {
246 ComposerEditorHandle,
247 ComposerEditorSelection,
248 ComposerTextPaste,
249} from "../native/T3ComposerEditor";