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
114function basename(path: string): string {
115 const separator = Math.max(path.lastIndexOf("/"), path.lastIndexOf("\\"));
116 return separator >= 0 ? path.slice(separator + 1) : path;
117}
118
119export function ComposerEditor({
120 ref,
121 skills = EMPTY_SKILLS,
122 selection,
123 style,
124 textStyle,
125 onChangeText,
126 onSelectionChange,
127 onPasteImages,
128 onPasteText,
129 onFocus,
130 onBlur,
131 onSubmit,
132 onContentSizeChange,
133 contentInsetVertical = 0,
134 ...props
135}: ComposerEditorProps) {
136 const nativeRef = useRef<NativeComposerEditorRef>(null);
137 const mostRecentEventCountRef = useRef(0);
138 const [mostRecentEventCount, setMostRecentEventCount] = useState(0);
139 const [, forceNativeEventRender] = useState(0);
140 // Start history empty so restored drafts or recycled views receive a non-echo controlled payload.
141 const nativeEventSnapshotsRef = useRef<ComposerNativeEventSnapshot[]>([]);
142 const confirmedTokensRef = useRef(collectComposerInlineTokens(props.value));
143 const bodyText = useScaledTextRole("body");
144 const theme = useUniwindTheme();
145 const fontFamily = FONT_FAMILIES.regular;
146
147 useImperativeHandle(
148 ref,
149 () => ({
150 focus: () => void nativeRef.current?.focus(),
151 blur: () => void nativeRef.current?.blur(),
152 setSelection: (nextSelection) =>
153 void nativeRef.current?.setSelection(nextSelection.start, nextSelection.end),
154 }),
155 [],
156 );
157
158 const skillLabels = useMemo(() => composerSkillLabels(skills), [skills]);
159 const chipTextColor = createNativeComposerTheme(theme).text;
160 const tokensJson = useMemo(() => {
161 const tokens = collectComposerInlineTokens(props.value, {
162 preserveTrailingFrom: confirmedTokensRef.current,
163 });
164 confirmedTokensRef.current = tokens;
165 return JSON.stringify(
166 composerContextEditorTokens(props.value, tokens, skillLabels).map((token) => {
167 const record =
168 token.type === "context"
169 ? props.context?.records.find((record) => record.contextId === token.contextId)
170 : undefined;
171 const presentation = contextChipPresentation(
172 token.type === "context" ? token.kind : token.type,
173 record,
174 );
175 const icon = contextChipIcon(
176 presentation,
177 token.type === "mention" ? token.value : contextRecordFileName(record),
178 );
179 return {
180 type: token.type,
181 source: token.source,
182 start: token.start,
183 end: token.end,
184 accent: contextChipAccent(presentation.accent, theme, chipTextColor),
185 label:
186 token.type === "skill"
187 ? (skillLabels.get(token.value) ?? token.value)
188 : token.type === "context"
189 ? `${token.label}${props.context?.records.some((record) => record.contextId === token.contextId) ? "" : " · unavailable"}`
190 : basename(token.value),
191 detail: token.type === "context" ? composerChipSizeSuffix(record) : "",
192 iconUri: contextChipIconUri(icon),
193 tintsIcon: icon.kind === "chip",
194 };
195 }),
196 );
197 }, [props.value, props.context, skillLabels, theme, chipTextColor]);
198 // Every render resolves against the snapshot history, so a render whose
199 // (value, selection) lags the acknowledged native state is stamped behind
200 // the native revision and rejected by the editor instead of re-applying a
201 // stale caret or stale text mid-typing.
202 const controlledEventCount = resolveComposerControlledEventCount(
203 props.value,
204 selection ?? null,
205 mostRecentEventCount,
206 nativeEventSnapshotsRef.current,
207 );
208 const acknowledgesLatestNativeEvent = isComposerNativeEcho(
209 props.value,
210 selection ?? null,
211 mostRecentEventCount,
212 nativeEventSnapshotsRef.current,
213 );
214 const isNativeEcho =
215 controlledEventCount === mostRecentEventCount && acknowledgesLatestNativeEvent;
216 const controlledDocumentJson = JSON.stringify({
217 value: props.value,
218 selection: isNativeEcho ? null : (selection ?? null),
219 tokensJson,
220 mostRecentEventCount: controlledEventCount,
221 isNativeEcho,
222 });
223 useEffect(() => {
224 if (!acknowledgesLatestNativeEvent) return;
225 nativeEventSnapshotsRef.current = pruneAcknowledgedComposerNativeEvents(
226 nativeEventSnapshotsRef.current,
227 mostRecentEventCount,
228 );
229 }, [acknowledgesLatestNativeEvent, mostRecentEventCount]);
230 const assumedValue = props.value;
231 useEffect(() => {
232 // Newer native events make this payload stale; do not record it as applied.
233 if (isNativeEcho || controlledEventCount !== mostRecentEventCountRef.current) return;
234 nativeEventSnapshotsRef.current = assumeComposerControlledState(
235 nativeEventSnapshotsRef.current,
236 controlledEventCount,
237 assumedValue,
238 );
239 }, [assumedValue, controlledEventCount, isNativeEcho, controlledDocumentJson]);
240 const acceptNativeEvent = useCallback(
241 (eventCount: number, value: string, nextSelection: ComposerEditorSelection) => {
242 const acknowledgedEventCount = acknowledgeComposerNativeEvent(
243 mostRecentEventCountRef.current,
244 eventCount,
245 );
246 if (acknowledgedEventCount === null) {
247 return false;
248 }
249 mostRecentEventCountRef.current = acknowledgedEventCount;
250 nativeEventSnapshotsRef.current.push({
251 eventCount: acknowledgedEventCount,
252 value,
253 selection: nextSelection,
254 });
255 return acknowledgedEventCount;
256 },
257 [],
258 );
259 const themeJson = JSON.stringify(createNativeComposerTheme(theme));
260 const resolvedTextStyle = StyleSheet.flatten(textStyle) ?? {};
261 return (
262 <NativeView
263 ref={nativeRef}
264 controlledDocumentJson={controlledDocumentJson}
265 clipboardFragment={props.clipboardFragment ?? ""}
266 themeJson={themeJson}
267 placeholder={props.placeholder ?? ""}
268 fontFamily={
269 typeof resolvedTextStyle.fontFamily === "string" ? resolvedTextStyle.fontFamily : fontFamily
270 }
271 fontSize={
272 typeof resolvedTextStyle.fontSize === "number"
273 ? resolvedTextStyle.fontSize
274 : bodyText.fontSize
275 }
276 lineHeight={
277 typeof resolvedTextStyle.lineHeight === "number"
278 ? resolvedTextStyle.lineHeight
279 : bodyText.lineHeight
280 }
281 contentInsetVertical={contentInsetVertical}
282 editable={props.editable ?? true}
283 readOnly={props.readOnly ?? false}
284 enterBehavior={props.enterBehavior ?? DEFAULT_COMPOSER_ENTER_BEHAVIOR}
285 submitTitle={props.submitTitle ?? "Send Message"}
286 alternateSubmitTitle={props.alternateSubmitTitle ?? props.submitTitle ?? "Send Message"}
287 scrollEnabled={props.scrollEnabled ?? true}
288 autoFocus={props.autoFocus ?? false}
289 autoCorrect={props.autoCorrect ?? true}
290 spellCheck={props.spellCheck ?? true}
291 textPasteThresholdBytes={onPasteText ? PASTED_TEXT_ATTACHMENT_THRESHOLD_BYTES : 0}
292 maxInputChars={PROVIDER_SEND_TURN_MAX_INPUT_CHARS}
293 style={style as StyleProp<ViewStyle>}
294 onComposerChange={(event) => {
295 const acknowledgedEventCount = acceptNativeEvent(
296 event.nativeEvent.eventCount,
297 event.nativeEvent.value,
298 event.nativeEvent.selection,
299 );
300 if (acknowledgedEventCount === false) return;
301 onChangeText(event.nativeEvent.value);
302 onSelectionChange?.(event.nativeEvent.selection);
303 setMostRecentEventCount(acknowledgedEventCount);
304 forceNativeEventRender((sequence) => sequence + 1);
305 }}
306 onComposerSelectionChange={(event) => {
307 const acknowledgedEventCount = acceptNativeEvent(
308 event.nativeEvent.eventCount,
309 event.nativeEvent.value,
310 event.nativeEvent.selection,
311 );
312 if (acknowledgedEventCount === false) return;
313 // Selection events may carry post-edit text; publish it with its revision or stale drafts can overwrite native text.
314 if (event.nativeEvent.value !== props.value) {
315 onChangeText(event.nativeEvent.value);
316 }
317 onSelectionChange?.(event.nativeEvent.selection);
318 setMostRecentEventCount(acknowledgedEventCount);
319 forceNativeEventRender((sequence) => sequence + 1);
320 }}
321 onComposerPasteImages={(event) => onPasteImages?.(event.nativeEvent.uris)}
322 onComposerContextPress={(event) => props.onContextPress?.(event.nativeEvent)}
323 onComposerPasteContext={(event) => {
324 const paste = event.nativeEvent;
325 const acknowledgedEventCount = acceptNativeEvent(
326 paste.eventCount,
327 paste.value,
328 paste.selection,
329 );
330 if (acknowledgedEventCount === false) return;
331 onChangeText(paste.value);
332 onSelectionChange?.(paste.selection);
333 props.onPasteContext?.(paste);
334 setMostRecentEventCount(acknowledgedEventCount);
335 forceNativeEventRender((sequence) => sequence + 1);
336 }}
337 onComposerPasteText={(event) => {
338 const paste = event.nativeEvent;
339 const acknowledgedEventCount = acceptNativeEvent(
340 paste.eventCount,
341 paste.value,
342 paste.selection,
343 );
344 if (acknowledgedEventCount === false) return;
345 // Sync before capturing async paste targets; props may lag the last native keystroke.
346 onChangeText(paste.value);
347 onSelectionChange?.(paste.selection);
348 onPasteText?.(paste);
349 setMostRecentEventCount(acknowledgedEventCount);
350 forceNativeEventRender((sequence) => sequence + 1);
351 }}
352 onComposerFocus={onFocus}
353 onComposerBlur={onBlur}
354 onComposerContentSizeChange={
355 onContentSizeChange === undefined
356 ? undefined
357 : (event) => onContentSizeChange(event.nativeEvent)
358 }
359 onComposerSubmit={
360 onSubmit === undefined
361 ? undefined
362 : (event) => onSubmit(event.nativeEvent.alternate === true)
363 }
364 />
365 );
366}
367
368export type {
369 ComposerEditorHandle,
370 ComposerEditorProps,
371 ComposerEditorSelection,
372 ComposerTextPaste,
373} from "./T3ComposerEditor.types";