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