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

main
tsx 435 lines 16.9 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 { DEFAULT_COMPOSER_ENTER_BEHAVIOR } from "../lib/composerEnterBehavior";
6 import { useComposerModelTokens } from "./useComposerModelTokens";
7 import { requireNativeView } from "expo";
8 import { TextInputWrapper } from "expo-paste-input";
9 import {
10 useCallback,
11 useEffect,
12 useImperativeHandle,
13 useMemo,
14 useRef,
15 useState,
16 type Ref,
17 } from "react";
18 import type { NativeSyntheticEvent, ViewProps } from "react-native";
19 import { Platform, StyleSheet } from "react-native";
20
21 import {
22 composerChipSizeSuffix,
23 contextChipIcon,
24 contextChipAccent,
25 contextChipPresentation,
26 contextRecordFileName,
27 } from "../lib/composerChipPresentation";
28 import { contextChipIconUri, modelChipIcon, modelChipIconUri } from "../lib/contextChipIconSource";
29 import { MOBILE_TYPOGRAPHY } from "../lib/typography";
30 import { useNativePaste } from "../lib/useNativePaste";
31 import { FONT_FAMILIES } from "../lib/fontFamilies";
32 import { useAppearancePreferences } from "../features/settings/appearance/AppearancePreferencesProvider";
33 import { useUniwindTheme } from "../lib/useUniwindTheme";
34 import { createNativeComposerTheme } from "../lib/nativeComposerTheme";
35 import {
36 acknowledgeComposerNativeEvent,
37 assumeComposerControlledState,
38 isComposerNativeEcho,
39 pruneAcknowledgedComposerNativeEvents,
40 resolveComposerControlledEventCount,
41 type ComposerNativeEventSnapshot,
42 } from "./composerEditorRevision";
43 import type { ComposerEditorProps, ComposerEditorSelection } from "./T3ComposerEditor.types";
44
45 const NATIVE_MODULE_NAME = "T3ComposerEditor";
46 const EMPTY_SKILLS: NonNullable<ComposerEditorProps["skills"]> = [];
47 const EMPTY_MODELS: NonNullable<ComposerEditorProps["models"]> = [];
48
49 type NativeEditorEvent = NativeSyntheticEvent<{
50 readonly value: string;
51 readonly selection: ComposerEditorSelection;
52 readonly eventCount: number;
53 }>;
54
55 type NativeSelectionEvent = NativeSyntheticEvent<{
56 readonly value: string;
57 readonly selection: ComposerEditorSelection;
58 readonly eventCount: number;
59 }>;
60
61 type NativePasteImagesEvent = NativeSyntheticEvent<{
62 readonly uris: ReadonlyArray<string>;
63 }>;
64
65 type NativePasteTextEvent = NativeSyntheticEvent<{
66 readonly value: string;
67 readonly eventCount: number;
68 readonly text: string;
69 readonly selection: ComposerEditorSelection;
70 }>;
71
72 interface NativeComposerEditorRef {
73 focus: () => Promise<void>;
74 blur: () => Promise<void>;
75 setSelection: (start: number, end: number) => Promise<void>;
76 }
77
78 interface NativeComposerEditorProps extends ViewProps {
79 readonly ref?: Ref<NativeComposerEditorRef>;
80 readonly controlledDocumentJson: string;
81 readonly clipboardFragment: string;
82 readonly themeJson: string;
83 readonly placeholder: string;
84 readonly fontFamily: string;
85 readonly fontSize: number;
86 readonly lineHeight: number;
87 readonly contentInsetVertical: number;
88 readonly singleLineCentered: boolean;
89 readonly editable: boolean;
90 readonly readOnly: boolean;
91 readonly scrollEnabled: boolean;
92 readonly autoFocus: boolean;
93 readonly autoCorrect: boolean;
94 readonly spellCheck: boolean;
95 readonly enterBehavior: string;
96 readonly submitEnabled: boolean;
97 readonly onComposerChange: (event: NativeEditorEvent) => void;
98 readonly onComposerSelectionChange?: (event: NativeSelectionEvent) => void;
99 readonly onComposerPasteImages?: (event: NativePasteImagesEvent) => void;
100 readonly onComposerContextPress?: (
101 event: NativeSyntheticEvent<{ source: string; start: number; end: number }>,
102 ) => void;
103 readonly onComposerPasteContext?: (
104 event: NativePasteTextEvent & NativeSyntheticEvent<{ fragment: string; html: string }>,
105 ) => void;
106 readonly textPasteThresholdBytes: number;
107 readonly maxInputChars: number;
108 readonly onComposerPasteText?: (event: NativePasteTextEvent) => void;
109 readonly onComposerFocus?: () => void;
110 readonly onComposerBlur?: () => void;
111 readonly onComposerContentSizeChange?: (
112 event: NativeSyntheticEvent<{ readonly width: number; readonly height: number }>,
113 ) => void;
114 readonly onComposerSubmit?: (event: NativeSyntheticEvent<{ alternate: boolean }>) => void;
115 }
116
117 const NativeView = requireNativeView<NativeComposerEditorProps>(NATIVE_MODULE_NAME);
118
119 // A view command rejects with "Unable to find the view" when the composer's native view is
120 // unmounted, which can happen while an open question hides the composer slot. There is nothing
121 // to act on then.
122 function settleViewCommand(command: Promise<void> | undefined): void {
123 command?.catch(() => undefined);
124 }
125
126 function basename(path: string): string {
127 const separator = Math.max(path.lastIndexOf("/"), path.lastIndexOf("\\"));
128 return separator >= 0 ? path.slice(separator + 1) : path;
129 }
130
131 export function ComposerEditor({
132 ref,
133 skills = EMPTY_SKILLS,
134 models = EMPTY_MODELS,
135 selection,
136 style,
137 textStyle,
138 onChangeText,
139 onSelectionChange,
140 onPasteImages,
141 onPasteText,
142 onFocus,
143 onBlur,
144 onContentSizeChange,
145 onSubmit,
146 contentInsetVertical = 0,
147 ...props
148 }: ComposerEditorProps) {
149 const nativeRef = useRef<NativeComposerEditorRef>(null);
150 const mostRecentEventCountRef = useRef(0);
151 const [mostRecentEventCount, setMostRecentEventCount] = useState(0);
152 const [, forceNativeEventRender] = useState(0);
153 // Start history empty so restored drafts or recycled views receive a non-echo controlled payload.
154 const nativeEventSnapshotsRef = useRef<ComposerNativeEventSnapshot[]>([]);
155 // Tokens advance from the previous committed value; render-phase state keeps
156 // an abandoned render from leaking a trailing token into the next one.
157 const [confirmedTokens, setConfirmedTokens] = useState(() => ({
158 value: props.value,
159 tokens: collectComposerInlineTokens(props.value),
160 }));
161 let tokens = confirmedTokens.tokens;
162 if (confirmedTokens.value !== props.value) {
163 tokens = collectComposerInlineTokens(props.value, {
164 preserveTrailingFrom: confirmedTokens.tokens,
165 });
166 setConfirmedTokens({ value: props.value, tokens });
167 }
168 const theme = useUniwindTheme();
169 const handlePaste = useNativePaste((uris) => onPasteImages?.(uris));
170
171 useImperativeHandle(
172 ref,
173 () => ({
174 focus: () => settleViewCommand(nativeRef.current?.focus()),
175 blur: () => settleViewCommand(nativeRef.current?.blur()),
176 setSelection: (nextSelection) =>
177 settleViewCommand(nativeRef.current?.setSelection(nextSelection.start, nextSelection.end)),
178 flushPendingInput: async () => {},
179 }),
180 [],
181 );
182
183 const skillLabels = useMemo(() => composerSkillLabels(skills), [skills]);
184 const { modelsBySource, modelTokens } = useComposerModelTokens(props.value, models);
185 const chipTextColor = createNativeComposerTheme(theme).text;
186 const tokensJson = useMemo(() => {
187 return JSON.stringify(
188 composerContextEditorTokens(props.value, tokens, skillLabels, modelTokens).map((token) => {
189 const model = token.type === "model" ? modelsBySource.get(token.source) : undefined;
190 const record =
191 token.type === "context"
192 ? props.context?.records.find((record) => record.contextId === token.contextId)
193 : undefined;
194 const presentation = contextChipPresentation(
195 token.type === "context" ? token.kind : token.type,
196 record,
197 );
198 const icon = contextChipIcon(
199 presentation,
200 token.type === "mention" ? token.value : contextRecordFileName(record),
201 );
202 return {
203 // Android taps only known token types; a model chip opens like a skill chip.
204 type:
205 token.type === "model" ? "skill" : 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 controlledEventCount = resolveComposerControlledEventCount(
246 props.value,
247 selection ?? null,
248 mostRecentEventCount,
249 nativeEventSnapshotsRef.current,
250 );
251 const acknowledgesLatestNativeEvent = isComposerNativeEcho(
252 props.value,
253 selection ?? null,
254 mostRecentEventCount,
255 nativeEventSnapshotsRef.current,
256 );
257 /* oxlint-enable react/refs */
258 const isNativeEcho =
259 controlledEventCount === mostRecentEventCount && acknowledgesLatestNativeEvent;
260 const controlledDocumentJson = JSON.stringify({
261 value: props.value,
262 selection: isNativeEcho ? null : (selection ?? null),
263 tokensJson,
264 mostRecentEventCount: controlledEventCount,
265 isNativeEcho,
266 });
267 // oxlint-disable-next-line t3code/no-unreasoned-state-sync -- prunes native editor event snapshots once a committed payload acknowledges them
268 useEffect(() => {
269 if (!acknowledgesLatestNativeEvent) return;
270 nativeEventSnapshotsRef.current = pruneAcknowledgedComposerNativeEvents(
271 nativeEventSnapshotsRef.current,
272 mostRecentEventCount,
273 );
274 }, [acknowledgesLatestNativeEvent, mostRecentEventCount, nativeEventSnapshotsRef]);
275 const assumedValue = props.value;
276 // oxlint-disable-next-line t3code/no-unreasoned-state-sync -- records the committed controlled payload as the native editor's assumed state
277 useEffect(() => {
278 // Newer native events make this payload stale; do not record it as applied.
279 if (isNativeEcho || controlledEventCount !== mostRecentEventCountRef.current) return;
280 nativeEventSnapshotsRef.current = assumeComposerControlledState(
281 nativeEventSnapshotsRef.current,
282 controlledEventCount,
283 assumedValue,
284 );
285 }, [
286 assumedValue,
287 controlledEventCount,
288 isNativeEcho,
289 // oxlint-disable-next-line react/exhaustive-effect-dependencies -- Every changed native payload, including selection-only changes, must update the assumed native snapshot.
290 controlledDocumentJson,
291 nativeEventSnapshotsRef,
292 ]);
293 const acceptNativeEvent = useCallback(
294 (eventCount: number, value: string, nextSelection: ComposerEditorSelection) => {
295 const acknowledgedEventCount = acknowledgeComposerNativeEvent(
296 mostRecentEventCountRef.current,
297 eventCount,
298 );
299 if (acknowledgedEventCount === null) {
300 return false;
301 }
302 mostRecentEventCountRef.current = acknowledgedEventCount;
303 nativeEventSnapshotsRef.current.push({
304 eventCount: acknowledgedEventCount,
305 value,
306 selection: nextSelection,
307 });
308 return acknowledgedEventCount;
309 },
310 [nativeEventSnapshotsRef],
311 );
312 const { systemColorsActive } = useAppearancePreferences();
313 const themeJson = JSON.stringify({
314 ...createNativeComposerTheme(theme),
315 selection: Platform.OS === "android" || systemColorsActive ? theme["--color-focus"] : null,
316 });
317 const resolvedTextStyle = StyleSheet.flatten(textStyle) ?? {};
318 const regularFontFamily = FONT_FAMILIES.regular;
319 return (
320 <TextInputWrapper onPaste={handlePaste} style={[{ minHeight: 0 }, style]}>
321 <NativeView
322 ref={nativeRef}
323 controlledDocumentJson={controlledDocumentJson}
324 clipboardFragment={props.clipboardFragment ?? ""}
325 themeJson={themeJson}
326 placeholder={props.placeholder ?? ""}
327 fontFamily={
328 typeof resolvedTextStyle.fontFamily === "string"
329 ? resolvedTextStyle.fontFamily
330 : regularFontFamily
331 }
332 fontSize={
333 typeof resolvedTextStyle.fontSize === "number"
334 ? resolvedTextStyle.fontSize
335 : MOBILE_TYPOGRAPHY.body.fontSize
336 }
337 lineHeight={
338 typeof resolvedTextStyle.lineHeight === "number"
339 ? resolvedTextStyle.lineHeight
340 : MOBILE_TYPOGRAPHY.body.lineHeight
341 }
342 contentInsetVertical={contentInsetVertical}
343 singleLineCentered={props.singleLineCentered ?? false}
344 editable={props.editable ?? true}
345 readOnly={props.readOnly ?? false}
346 scrollEnabled={props.scrollEnabled ?? true}
347 autoFocus={props.autoFocus ?? false}
348 autoCorrect={props.autoCorrect ?? true}
349 spellCheck={props.spellCheck ?? true}
350 enterBehavior={props.enterBehavior ?? DEFAULT_COMPOSER_ENTER_BEHAVIOR}
351 submitEnabled={onSubmit !== undefined}
352 textPasteThresholdBytes={onPasteText ? PASTED_TEXT_ATTACHMENT_THRESHOLD_BYTES : 0}
353 maxInputChars={PROVIDER_SEND_TURN_MAX_INPUT_CHARS}
354 style={{ flex: 1, minHeight: 0 }}
355 onComposerChange={(event) => {
356 const acknowledgedEventCount = acceptNativeEvent(
357 event.nativeEvent.eventCount,
358 event.nativeEvent.value,
359 event.nativeEvent.selection,
360 );
361 if (acknowledgedEventCount === false) return;
362 onChangeText(event.nativeEvent.value);
363 onSelectionChange?.(event.nativeEvent.selection);
364 setMostRecentEventCount(acknowledgedEventCount);
365 forceNativeEventRender((sequence) => sequence + 1);
366 }}
367 onComposerSelectionChange={(event) => {
368 const acknowledgedEventCount = acceptNativeEvent(
369 event.nativeEvent.eventCount,
370 event.nativeEvent.value,
371 event.nativeEvent.selection,
372 );
373 if (acknowledgedEventCount === false) return;
374 // Android selection events may precede text changes; publish text and revision together to reject stale drafts.
375 if (event.nativeEvent.value !== props.value) {
376 onChangeText(event.nativeEvent.value);
377 }
378 onSelectionChange?.(event.nativeEvent.selection);
379 setMostRecentEventCount(acknowledgedEventCount);
380 forceNativeEventRender((sequence) => sequence + 1);
381 }}
382 onComposerPasteImages={(event) => onPasteImages?.(event.nativeEvent.uris)}
383 onComposerContextPress={(event) => props.onContextPress?.(event.nativeEvent)}
384 onComposerPasteContext={(event) => {
385 const paste = event.nativeEvent;
386 const acknowledgedEventCount = acceptNativeEvent(
387 paste.eventCount,
388 paste.value,
389 paste.selection,
390 );
391 if (acknowledgedEventCount === false) return;
392 onChangeText(paste.value);
393 onSelectionChange?.(paste.selection);
394 props.onPasteContext?.(paste);
395 setMostRecentEventCount(acknowledgedEventCount);
396 forceNativeEventRender((sequence) => sequence + 1);
397 }}
398 onComposerPasteText={(event) => {
399 const paste = event.nativeEvent;
400 const acknowledgedEventCount = acceptNativeEvent(
401 paste.eventCount,
402 paste.value,
403 paste.selection,
404 );
405 if (acknowledgedEventCount === false) return;
406 // Sync before capturing async paste targets; props may lag the last native keystroke.
407 onChangeText(paste.value);
408 onSelectionChange?.(paste.selection);
409 onPasteText?.(paste);
410 setMostRecentEventCount(acknowledgedEventCount);
411 forceNativeEventRender((sequence) => sequence + 1);
412 }}
413 onComposerFocus={onFocus}
414 onComposerBlur={onBlur}
415 onComposerContentSizeChange={
416 onContentSizeChange === undefined
417 ? undefined
418 : (event) => onContentSizeChange(event.nativeEvent)
419 }
420 onComposerSubmit={
421 onSubmit === undefined
422 ? undefined
423 : (event) => onSubmit(event.nativeEvent.alternate === true)
424 }
425 />
426 </TextInputWrapper>
427 );
428 }
429
430 export type {
431 ComposerEditorHandle,
432 ComposerEditorProps,
433 ComposerEditorSelection,
434 ComposerTextPaste,
435 } from "./T3ComposerEditor.types";