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 // oxlint-disable-next-line t3code/no-unreasoned-state-sync -- prunes native editor event snapshots once a committed payload acknowledges them
241 useEffect(() => {
242 if (!acknowledgesLatestNativeEvent) return;
243 nativeEventSnapshotsRef.current = pruneAcknowledgedComposerNativeEvents(
244 nativeEventSnapshotsRef.current,
245 mostRecentEventCount,
246 );
247 }, [acknowledgesLatestNativeEvent, mostRecentEventCount, nativeEventSnapshotsRef]);
248 const assumedValue = props.value;
249 // oxlint-disable-next-line t3code/no-unreasoned-state-sync -- records the committed controlled payload as the native editor's assumed state
250 useEffect(() => {
251 // Newer native events make this payload stale; do not record it as applied.
252 if (isNativeEcho || controlledEventCount !== mostRecentEventCountRef.current) return;
253 nativeEventSnapshotsRef.current = assumeComposerControlledState(
254 nativeEventSnapshotsRef.current,
255 controlledEventCount,
256 assumedValue,
257 );
258 }, [
259 assumedValue,
260 controlledEventCount,
261 isNativeEcho,
262 // oxlint-disable-next-line react/exhaustive-effect-dependencies -- Every changed native payload, including selection-only changes, must update the assumed native snapshot.
263 controlledDocumentJson,
264 nativeEventSnapshotsRef,
265 ]);
266 const acceptNativeEvent = useCallback(
267 (eventCount: number, value: string, nextSelection: ComposerEditorSelection) => {
268 const acknowledgedEventCount = acknowledgeComposerNativeEvent(
269 mostRecentEventCountRef.current,
270 eventCount,
271 );
272 if (acknowledgedEventCount === null) {
273 return false;
274 }
275 mostRecentEventCountRef.current = acknowledgedEventCount;
276 nativeEventSnapshotsRef.current.push({
277 eventCount: acknowledgedEventCount,
278 value,
279 selection: nextSelection,
280 });
281 return acknowledgedEventCount;
282 },
283 [nativeEventSnapshotsRef],
284 );
285 const themeJson = JSON.stringify(createNativeComposerTheme(theme));
286 const resolvedTextStyle = StyleSheet.flatten(textStyle) ?? {};
287 return (
288 <NativeView
289 ref={nativeRef}
290 controlledDocumentJson={controlledDocumentJson}
291 clipboardFragment={props.clipboardFragment ?? ""}
292 themeJson={themeJson}
293 placeholder={props.placeholder ?? ""}
294 fontFamily={
295 typeof resolvedTextStyle.fontFamily === "string" ? resolvedTextStyle.fontFamily : fontFamily
296 }
297 fontSize={
298 typeof resolvedTextStyle.fontSize === "number"
299 ? resolvedTextStyle.fontSize
300 : bodyText.fontSize
301 }
302 lineHeight={
303 typeof resolvedTextStyle.lineHeight === "number"
304 ? resolvedTextStyle.lineHeight
305 : bodyText.lineHeight
306 }
307 contentInsetVertical={contentInsetVertical}
308 editable={props.editable ?? true}
309 readOnly={props.readOnly ?? false}
310 enterBehavior={props.enterBehavior ?? DEFAULT_COMPOSER_ENTER_BEHAVIOR}
311 submitTitle={props.submitTitle ?? "Send Message"}
312 alternateSubmitTitle={props.alternateSubmitTitle ?? props.submitTitle ?? "Send Message"}
313 scrollEnabled={props.scrollEnabled ?? true}
314 autoFocus={props.autoFocus ?? false}
315 autoCorrect={props.autoCorrect ?? true}
316 spellCheck={props.spellCheck ?? true}
317 textPasteThresholdBytes={onPasteText ? PASTED_TEXT_ATTACHMENT_THRESHOLD_BYTES : 0}
318 maxInputChars={PROVIDER_SEND_TURN_MAX_INPUT_CHARS}
319 style={style as StyleProp<ViewStyle>}
320 onComposerChange={(event) => {
321 const acknowledgedEventCount = acceptNativeEvent(
322 event.nativeEvent.eventCount,
323 event.nativeEvent.value,
324 event.nativeEvent.selection,
325 );
326 if (acknowledgedEventCount === false) return;
327 onChangeText(event.nativeEvent.value);
328 onSelectionChange?.(event.nativeEvent.selection);
329 setMostRecentEventCount(acknowledgedEventCount);
330 forceNativeEventRender((sequence) => sequence + 1);
331 }}
332 onComposerSelectionChange={(event) => {
333 const acknowledgedEventCount = acceptNativeEvent(
334 event.nativeEvent.eventCount,
335 event.nativeEvent.value,
336 event.nativeEvent.selection,
337 );
338 if (acknowledgedEventCount === false) return;
339 // Selection events may carry post-edit text; publish it with its revision or stale drafts can overwrite native text.
340 if (event.nativeEvent.value !== props.value) {
341 onChangeText(event.nativeEvent.value);
342 }
343 onSelectionChange?.(event.nativeEvent.selection);
344 setMostRecentEventCount(acknowledgedEventCount);
345 forceNativeEventRender((sequence) => sequence + 1);
346 }}
347 onComposerPasteImages={(event) => onPasteImages?.(event.nativeEvent.uris)}
348 onComposerContextPress={(event) => props.onContextPress?.(event.nativeEvent)}
349 onComposerPasteContext={(event) => {
350 const paste = event.nativeEvent;
351 const acknowledgedEventCount = acceptNativeEvent(
352 paste.eventCount,
353 paste.value,
354 paste.selection,
355 );
356 if (acknowledgedEventCount === false) return;
357 onChangeText(paste.value);
358 onSelectionChange?.(paste.selection);
359 props.onPasteContext?.(paste);
360 setMostRecentEventCount(acknowledgedEventCount);
361 forceNativeEventRender((sequence) => sequence + 1);
362 }}
363 onComposerPasteText={(event) => {
364 const paste = event.nativeEvent;
365 const acknowledgedEventCount = acceptNativeEvent(
366 paste.eventCount,
367 paste.value,
368 paste.selection,
369 );
370 if (acknowledgedEventCount === false) return;
371 // Sync before capturing async paste targets; props may lag the last native keystroke.
372 onChangeText(paste.value);
373 onSelectionChange?.(paste.selection);
374 onPasteText?.(paste);
375 setMostRecentEventCount(acknowledgedEventCount);
376 forceNativeEventRender((sequence) => sequence + 1);
377 }}
378 onComposerFocus={onFocus}
379 onComposerBlur={onBlur}
380 onComposerContentSizeChange={
381 onContentSizeChange === undefined
382 ? undefined
383 : (event) => onContentSizeChange(event.nativeEvent)
384 }
385 onComposerSubmit={
386 onSubmit === undefined
387 ? undefined
388 : (event) => onSubmit(event.nativeEvent.alternate === true)
389 }
390 />
391 );
392}
393
394export type {
395 ComposerEditorHandle,
396 ComposerEditorProps,
397 ComposerEditorSelection,
398 ComposerTextPaste,
399} from "./T3ComposerEditor.types";