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