The best way to control Claude Code, Codex and more from any computer or phone

main
tsx 438 lines 17.3 KB
Raw
1 import { PASTED_TEXT_ATTACHMENT_THRESHOLD_BYTES } from "@t3tools/client-runtime/text-paste";
2 import { PROVIDER_SEND_TURN_MAX_INPUT_CHARS } from "@t3tools/contracts";
3 import { collectComposerInlineTokens } from "@t3tools/shared/composerInlineTokens";
4 import { composerContextEditorTokens, composerSkillLabels } from "../lib/composerContext";
5 import { useComposerModelTokens } from "./useComposerModelTokens";
6 import { requireNativeView } from "expo";
7 import { useGT } from "gt-react-native";
8 import {
9 useCallback,
10 useEffect,
11 useImperativeHandle,
12 useMemo,
13 useRef,
14 useState,
15 type Ref,
16 } from "react";
17 import type { NativeSyntheticEvent, StyleProp, ViewProps, ViewStyle } from "react-native";
18 import { StyleSheet } from "react-native";
19
20 import {
21 composerChipSizeSuffix,
22 contextChipIcon,
23 contextChipAccent,
24 contextChipPresentation,
25 contextRecordFileName,
26 } from "../lib/composerChipPresentation";
27 import { contextChipIconUri, modelChipIcon, modelChipIconUri } from "../lib/contextChipIconSource";
28 import { useUniwindTheme } from "../lib/useUniwindTheme";
29 import { createNativeComposerTheme } from "../lib/nativeComposerTheme";
30 import { FONT_FAMILIES } from "../lib/fontFamilies";
31 import { useComposerTextRole } from "../features/settings/appearance/useScaledTextRole";
32 import {
33 acknowledgeComposerNativeEvent,
34 assumeComposerControlledState,
35 isComposerNativeEcho,
36 pruneAcknowledgedComposerNativeEvents,
37 resolveComposerControlledEventCount,
38 type ComposerNativeEventSnapshot,
39 } from "./composerEditorRevision";
40 import { DEFAULT_COMPOSER_ENTER_BEHAVIOR } from "../lib/composerEnterBehavior";
41 import type { ComposerEditorProps, ComposerEditorSelection } from "./T3ComposerEditor.types";
42
43 const NATIVE_MODULE_NAME = "T3ComposerEditor";
44 const EMPTY_SKILLS: NonNullable<ComposerEditorProps["skills"]> = [];
45 const EMPTY_MODELS: NonNullable<ComposerEditorProps["models"]> = [];
46 const NO_RESET = () => 0;
47
48 type NativeEditorEvent = NativeSyntheticEvent<{
49 readonly value: string;
50 readonly selection: ComposerEditorSelection;
51 readonly eventCount: number;
52 readonly resetGeneration: number;
53 }>;
54
55 type NativeSelectionEvent = NativeSyntheticEvent<{
56 readonly value: string;
57 readonly selection: ComposerEditorSelection;
58 readonly eventCount: number;
59 readonly resetGeneration: number;
60 }>;
61
62 type NativePasteImagesEvent = NativeSyntheticEvent<{
63 readonly uris: ReadonlyArray<string>;
64 }>;
65
66 type NativePasteTextEvent = NativeSyntheticEvent<{
67 readonly value: string;
68 readonly eventCount: number;
69 readonly resetGeneration: number;
70 readonly text: string;
71 readonly selection: ComposerEditorSelection;
72 }>;
73
74 interface NativeComposerEditorRef {
75 focus: () => Promise<void>;
76 blur: () => Promise<void>;
77 setSelection: (start: number, end: number) => Promise<void>;
78 readState: () => Promise<{
79 readonly value: string;
80 readonly selection: ComposerEditorSelection;
81 readonly eventCount: number;
82 readonly resetGeneration: number;
83 readonly pasteEventCount: number;
84 }>;
85 }
86
87 interface NativeComposerEditorProps extends ViewProps {
88 readonly ref?: Ref<NativeComposerEditorRef>;
89 readonly controlledDocumentJson: string;
90 readonly clipboardFragment: string;
91 readonly themeJson: string;
92 readonly placeholder: string;
93 readonly fontFamily: string;
94 readonly fontSize: number;
95 readonly lineHeight: number;
96 readonly contentInsetVertical: number;
97 readonly editable: boolean;
98 readonly readOnly: boolean;
99 readonly enterBehavior: string;
100 readonly submitTitle: string;
101 readonly alternateSubmitTitle: string;
102 readonly scrollEnabled: boolean;
103 readonly autoFocus: boolean;
104 readonly autoCorrect: boolean;
105 readonly spellCheck: boolean;
106 readonly onComposerChange: (event: NativeEditorEvent) => void;
107 readonly onComposerSelectionChange?: (event: NativeSelectionEvent) => void;
108 readonly onComposerPasteImages?: (event: NativePasteImagesEvent) => void;
109 readonly onComposerContextPress?: (
110 event: NativeSyntheticEvent<{ source: string; start: number; end: number }>,
111 ) => void;
112 readonly onComposerPasteContext?: (
113 event: NativePasteTextEvent & NativeSyntheticEvent<{ fragment: string; html: string }>,
114 ) => void;
115 readonly textPasteThresholdBytes: number;
116 readonly maxInputChars: number;
117 readonly onComposerPasteText?: (event: NativePasteTextEvent) => void;
118 readonly onComposerFocus?: () => void;
119 readonly onComposerBlur?: () => void;
120 readonly onComposerSubmit?: (event: NativeSyntheticEvent<{ alternate: boolean }>) => void;
121 readonly onComposerContentSizeChange?: (
122 event: NativeSyntheticEvent<{ readonly width: number; readonly height: number }>,
123 ) => void;
124 }
125
126 const NativeView = requireNativeView<NativeComposerEditorProps>(NATIVE_MODULE_NAME);
127
128 // A view command rejects with "Unable to find the view" when the composer's native view is
129 // unmounted, which can happen while an open question hides the composer slot. There is nothing
130 // to act on then.
131 function settleViewCommand(command: Promise<void> | undefined): void {
132 command?.catch(() => undefined);
133 }
134
135 function basename(path: string): string {
136 const separator = Math.max(path.lastIndexOf("/"), path.lastIndexOf("\\"));
137 return separator >= 0 ? path.slice(separator + 1) : path;
138 }
139
140 export function ComposerEditor({
141 ref,
142 skills = EMPTY_SKILLS,
143 models = EMPTY_MODELS,
144 selection,
145 style,
146 textStyle,
147 onChangeText,
148 onSelectionChange,
149 onPasteImages,
150 onPasteText,
151 onFocus,
152 onBlur,
153 onSubmit,
154 onContentSizeChange,
155 contentInsetVertical = 0,
156 readResetGeneration = NO_RESET,
157 ...props
158 }: ComposerEditorProps) {
159 const gt = useGT();
160 const nativeRef = useRef<NativeComposerEditorRef>(null);
161 const mostRecentEventCountRef = useRef(0);
162 const [mostRecentEventCount, setMostRecentEventCount] = useState(0);
163 const [, forceNativeEventRender] = useState(0);
164 // Native stamps every event with the reset generation it had applied.
165 const nativeResetGenerationRef = useRef(0);
166 // Start history empty so restored drafts or recycled views receive a non-echo controlled payload.
167 const nativeEventSnapshotsRef = useRef<ComposerNativeEventSnapshot[]>([]);
168 // Tokens advance from the previous committed value; render-phase state keeps
169 // an abandoned render from leaking a trailing token into the next one.
170 const [confirmedTokens, setConfirmedTokens] = useState(() => ({
171 value: props.value,
172 tokens: collectComposerInlineTokens(props.value),
173 }));
174 let tokens = confirmedTokens.tokens;
175 if (confirmedTokens.value !== props.value) {
176 tokens = collectComposerInlineTokens(props.value, {
177 preserveTrailingFrom: confirmedTokens.tokens,
178 });
179 setConfirmedTokens({ value: props.value, tokens });
180 }
181 const bodyText = useComposerTextRole();
182 const theme = useUniwindTheme();
183 const fontFamily = FONT_FAMILIES.regular;
184
185 const skillLabels = useMemo(() => composerSkillLabels(skills), [skills]);
186 const { modelsBySource, modelTokens } = useComposerModelTokens(props.value, models);
187 const chipTextColor = createNativeComposerTheme(theme).text;
188 const tokensJson = useMemo(() => {
189 return JSON.stringify(
190 composerContextEditorTokens(props.value, tokens, skillLabels, modelTokens).map((token) => {
191 const model = token.type === "model" ? modelsBySource.get(token.source) : undefined;
192 const record =
193 token.type === "context"
194 ? props.context?.records.find((record) => record.contextId === token.contextId)
195 : undefined;
196 const presentation = contextChipPresentation(
197 token.type === "context" ? token.kind : token.type,
198 record,
199 );
200 const icon = contextChipIcon(
201 presentation,
202 token.type === "mention" ? token.value : contextRecordFileName(record),
203 );
204 return {
205 type: token.type === "citation" ? "context" : token.type,
206 source: token.source,
207 start: token.start,
208 end: token.end,
209 accent: contextChipAccent(
210 model ? modelChipIcon(model).accent : presentation.accent,
211 theme,
212 chipTextColor,
213 ),
214 label:
215 token.type === "skill"
216 ? (skillLabels.get(token.value) ?? token.value)
217 : model
218 ? model.label
219 : token.type === "context"
220 ? `${token.label}${props.context?.records.some((record) => record.contextId === token.contextId) ? "" : " · unavailable"}`
221 : token.type === "citation"
222 ? token.value
223 : basename(token.value),
224 detail: token.type === "context" ? composerChipSizeSuffix(record) : "",
225 iconUri: model ? modelChipIconUri(model) : contextChipIconUri(icon),
226 tintsIcon: model ? modelChipIcon(model).tintsIcon : icon.kind === "chip",
227 };
228 }),
229 );
230 }, [
231 props.value,
232 tokens,
233 props.context,
234 skillLabels,
235 modelsBySource,
236 modelTokens,
237 theme,
238 chipTextColor,
239 ]);
240 // Every render resolves against the snapshot history, so a render whose
241 // (value, selection) lags the acknowledged native state is stamped behind
242 // the native revision and rejected by the editor instead of re-applying a
243 // stale caret or stale text mid-typing.
244 /* oxlint-disable react/refs -- Native controlled edits must reconcile against the last acknowledged native event before sending the next payload. */
245 const resetGeneration = readResetGeneration();
246 // Native restarts its revision at a reset's stamp, so stamp it at the latest acknowledged event.
247 const controlledEventCount =
248 resetGeneration > nativeResetGenerationRef.current
249 ? mostRecentEventCount
250 : resolveComposerControlledEventCount(
251 props.value,
252 selection ?? null,
253 mostRecentEventCount,
254 nativeEventSnapshotsRef.current,
255 );
256 const acknowledgesLatestNativeEvent = isComposerNativeEcho(
257 props.value,
258 selection ?? null,
259 mostRecentEventCount,
260 nativeEventSnapshotsRef.current,
261 );
262 /* oxlint-enable react/refs */
263 const isNativeEcho =
264 controlledEventCount === mostRecentEventCount && acknowledgesLatestNativeEvent;
265 const controlledDocumentJson = JSON.stringify({
266 value: props.value,
267 selection: isNativeEcho ? null : (selection ?? null),
268 tokensJson,
269 mostRecentEventCount: controlledEventCount,
270 isNativeEcho,
271 resetGeneration,
272 });
273 // oxlint-disable-next-line t3code/no-unreasoned-state-sync -- prunes native editor event snapshots once a committed payload acknowledges them
274 useEffect(() => {
275 if (!acknowledgesLatestNativeEvent) return;
276 nativeEventSnapshotsRef.current = pruneAcknowledgedComposerNativeEvents(
277 nativeEventSnapshotsRef.current,
278 mostRecentEventCount,
279 );
280 }, [acknowledgesLatestNativeEvent, mostRecentEventCount, nativeEventSnapshotsRef]);
281 const assumedValue = props.value;
282 // oxlint-disable-next-line t3code/no-unreasoned-state-sync -- records the committed controlled payload as the native editor's assumed state
283 useEffect(() => {
284 // Newer native events make this payload stale; do not record it as applied.
285 if (isNativeEcho || controlledEventCount !== mostRecentEventCountRef.current) return;
286 nativeEventSnapshotsRef.current = assumeComposerControlledState(
287 nativeEventSnapshotsRef.current,
288 controlledEventCount,
289 assumedValue,
290 );
291 }, [
292 assumedValue,
293 controlledEventCount,
294 isNativeEcho,
295 // oxlint-disable-next-line react/exhaustive-effect-dependencies -- Every changed native payload, including selection-only changes, must update the assumed native snapshot.
296 controlledDocumentJson,
297 nativeEventSnapshotsRef,
298 ]);
299 const acceptNativeEvent = useCallback(
300 (event: NativeEditorEvent["nativeEvent"]) => {
301 // Read at delivery: a send can clear the draft in the same batch, before this view re-renders.
302 const acknowledgedEventCount = acknowledgeComposerNativeEvent(
303 mostRecentEventCountRef.current,
304 event.eventCount,
305 readResetGeneration(),
306 event.resetGeneration,
307 );
308 if (acknowledgedEventCount === null) {
309 return false;
310 }
311 mostRecentEventCountRef.current = acknowledgedEventCount;
312 nativeResetGenerationRef.current = event.resetGeneration;
313 nativeEventSnapshotsRef.current.push({
314 eventCount: acknowledgedEventCount,
315 value: event.value,
316 selection: event.selection,
317 });
318 return acknowledgedEventCount;
319 },
320 [nativeEventSnapshotsRef, readResetGeneration],
321 );
322 const applyNativeChange = (event: NativeEditorEvent["nativeEvent"]) => {
323 const acknowledgedEventCount = acceptNativeEvent(event);
324 if (acknowledgedEventCount === false) return;
325 onChangeText(event.value);
326 onSelectionChange?.(event.selection);
327 setMostRecentEventCount(acknowledgedEventCount);
328 forceNativeEventRender((sequence) => sequence + 1);
329 };
330 useImperativeHandle(ref, () => ({
331 focus: () => settleViewCommand(nativeRef.current?.focus()),
332 blur: () => settleViewCommand(nativeRef.current?.blur()),
333 setSelection: (nextSelection) =>
334 settleViewCommand(nativeRef.current?.setSelection(nextSelection.start, nextSelection.end)),
335 // Tapping outside the editor makes iOS accept a pending autocorrection, and that edit's
336 // event can reach JS after the tap's handler has already read the draft.
337 flushPendingInput: async () => {
338 const state = await Promise.resolve()
339 .then(() => nativeRef.current?.readState())
340 .catch(() => undefined);
341 // Acknowledging past a paste JS has not received yet would get the paste rejected.
342 if (state && state.pasteEventCount <= mostRecentEventCountRef.current) {
343 applyNativeChange(state);
344 }
345 },
346 }));
347 const themeJson = JSON.stringify(createNativeComposerTheme(theme));
348 const resolvedTextStyle = StyleSheet.flatten(textStyle) ?? {};
349 return (
350 <NativeView
351 ref={nativeRef}
352 controlledDocumentJson={controlledDocumentJson}
353 clipboardFragment={props.clipboardFragment ?? ""}
354 themeJson={themeJson}
355 placeholder={props.placeholder ?? ""}
356 fontFamily={
357 typeof resolvedTextStyle.fontFamily === "string" ? resolvedTextStyle.fontFamily : fontFamily
358 }
359 fontSize={
360 typeof resolvedTextStyle.fontSize === "number"
361 ? resolvedTextStyle.fontSize
362 : bodyText.fontSize
363 }
364 lineHeight={
365 typeof resolvedTextStyle.lineHeight === "number"
366 ? resolvedTextStyle.lineHeight
367 : bodyText.lineHeight
368 }
369 contentInsetVertical={contentInsetVertical}
370 editable={props.editable ?? true}
371 readOnly={props.readOnly ?? false}
372 enterBehavior={props.enterBehavior ?? DEFAULT_COMPOSER_ENTER_BEHAVIOR}
373 submitTitle={props.submitTitle ?? gt("Send Message")}
374 alternateSubmitTitle={props.alternateSubmitTitle ?? props.submitTitle ?? gt("Send Message")}
375 scrollEnabled={props.scrollEnabled ?? true}
376 autoFocus={props.autoFocus ?? false}
377 autoCorrect={props.autoCorrect ?? true}
378 spellCheck={props.spellCheck ?? true}
379 textPasteThresholdBytes={onPasteText ? PASTED_TEXT_ATTACHMENT_THRESHOLD_BYTES : 0}
380 maxInputChars={PROVIDER_SEND_TURN_MAX_INPUT_CHARS}
381 style={style as StyleProp<ViewStyle>}
382 onComposerChange={(event) => applyNativeChange(event.nativeEvent)}
383 onComposerSelectionChange={(event) => {
384 const acknowledgedEventCount = acceptNativeEvent(event.nativeEvent);
385 if (acknowledgedEventCount === false) return;
386 // Selection events may carry post-edit text; publish it with its revision or stale drafts can overwrite native text.
387 if (event.nativeEvent.value !== props.value) {
388 onChangeText(event.nativeEvent.value);
389 }
390 onSelectionChange?.(event.nativeEvent.selection);
391 setMostRecentEventCount(acknowledgedEventCount);
392 forceNativeEventRender((sequence) => sequence + 1);
393 }}
394 onComposerPasteImages={(event) => onPasteImages?.(event.nativeEvent.uris)}
395 onComposerContextPress={(event) => props.onContextPress?.(event.nativeEvent)}
396 onComposerPasteContext={(event) => {
397 const paste = event.nativeEvent;
398 const acknowledgedEventCount = acceptNativeEvent(paste);
399 if (acknowledgedEventCount === false) return;
400 onChangeText(paste.value);
401 onSelectionChange?.(paste.selection);
402 props.onPasteContext?.(paste);
403 setMostRecentEventCount(acknowledgedEventCount);
404 forceNativeEventRender((sequence) => sequence + 1);
405 }}
406 onComposerPasteText={(event) => {
407 const paste = event.nativeEvent;
408 const acknowledgedEventCount = acceptNativeEvent(paste);
409 if (acknowledgedEventCount === false) return;
410 // Sync before capturing async paste targets; props may lag the last native keystroke.
411 onChangeText(paste.value);
412 onSelectionChange?.(paste.selection);
413 onPasteText?.(paste);
414 setMostRecentEventCount(acknowledgedEventCount);
415 forceNativeEventRender((sequence) => sequence + 1);
416 }}
417 onComposerFocus={onFocus}
418 onComposerBlur={onBlur}
419 onComposerContentSizeChange={
420 onContentSizeChange === undefined
421 ? undefined
422 : (event) => onContentSizeChange(event.nativeEvent)
423 }
424 onComposerSubmit={
425 onSubmit === undefined
426 ? undefined
427 : (event) => onSubmit(event.nativeEvent.alternate === true)
428 }
429 />
430 );
431 }
432
433 export type {
434 ComposerEditorHandle,
435 ComposerEditorProps,
436 ComposerEditorSelection,
437 ComposerTextPaste,
438 } from "./T3ComposerEditor.types";