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