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