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