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