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