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