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 contextChipPresentation,
22 contextRecordFileName,
23} from "../lib/composerChipPresentation";
24import { contextChipIconUri } from "../lib/contextChipIconSource";
25import { useUniwindTheme } from "../lib/useUniwindTheme";
26import { createNativeComposerTheme } from "../lib/nativeComposerTheme";
27import { FONT_FAMILIES } from "../lib/fontFamilies";
28import { useScaledTextRole } from "../features/settings/appearance/useScaledTextRole";
29import {
30 acknowledgeComposerNativeEvent,
31 assumeComposerControlledState,
32 isComposerNativeEcho,
33 pruneAcknowledgedComposerNativeEvents,
34 resolveComposerControlledEventCount,
35 type ComposerNativeEventSnapshot,
36} from "./composerEditorRevision";
37import { DEFAULT_COMPOSER_ENTER_BEHAVIOR } from "../lib/composerEnterBehavior";
38import type { ComposerEditorProps, ComposerEditorSelection } from "./T3ComposerEditor.types";
39
40const NATIVE_MODULE_NAME = "T3ComposerEditor";
41const EMPTY_SKILLS: NonNullable<ComposerEditorProps["skills"]> = [];
42
43type NativeEditorEvent = NativeSyntheticEvent<{
44 readonly value: string;
45 readonly selection: ComposerEditorSelection;
46 readonly eventCount: number;
47}>;
48
49type NativeSelectionEvent = NativeSyntheticEvent<{
50 readonly value: string;
51 readonly selection: ComposerEditorSelection;
52 readonly eventCount: number;
53}>;
54
55type NativePasteImagesEvent = NativeSyntheticEvent<{
56 readonly uris: ReadonlyArray<string>;
57}>;
58
59type NativePasteTextEvent = NativeSyntheticEvent<{
60 readonly value: string;
61 readonly eventCount: number;
62 readonly text: string;
63 readonly selection: ComposerEditorSelection;
64}>;
65
66interface NativeComposerEditorRef {
67 focus: () => Promise<void>;
68 blur: () => Promise<void>;
69 setSelection: (start: number, end: number) => Promise<void>;
70}
71
72interface NativeComposerEditorProps extends ViewProps {
73 readonly ref?: Ref<NativeComposerEditorRef>;
74 readonly controlledDocumentJson: string;
75 readonly clipboardFragment: string;
76 readonly themeJson: string;
77 readonly placeholder: string;
78 readonly fontFamily: string;
79 readonly fontSize: number;
80 readonly lineHeight: number;
81 readonly contentInsetVertical: number;
82 readonly editable: boolean;
83 readonly readOnly: boolean;
84 readonly enterBehavior: string;
85 readonly submitTitle: string;
86 readonly alternateSubmitTitle: string;
87 readonly scrollEnabled: boolean;
88 readonly autoFocus: boolean;
89 readonly autoCorrect: boolean;
90 readonly spellCheck: boolean;
91 readonly onComposerChange: (event: NativeEditorEvent) => void;
92 readonly onComposerSelectionChange?: (event: NativeSelectionEvent) => void;
93 readonly onComposerPasteImages?: (event: NativePasteImagesEvent) => void;
94 readonly onComposerContextPress?: (
95 event: NativeSyntheticEvent<{ source: string; start: number; end: number }>,
96 ) => void;
97 readonly onComposerPasteContext?: (
98 event: NativePasteTextEvent & NativeSyntheticEvent<{ fragment: string; html: string }>,
99 ) => void;
100 readonly textPasteThresholdBytes: number;
101 readonly maxInputChars: number;
102 readonly onComposerPasteText?: (event: NativePasteTextEvent) => void;
103 readonly onComposerFocus?: () => void;
104 readonly onComposerBlur?: () => void;
105 readonly onComposerSubmit?: (event: NativeSyntheticEvent<{ alternate: boolean }>) => void;
106 readonly onComposerContentSizeChange?: (
107 event: NativeSyntheticEvent<{ readonly width: number; readonly height: number }>,
108 ) => void;
109}
110
111const NativeView = requireNativeView<NativeComposerEditorProps>(NATIVE_MODULE_NAME);
112
113function basename(path: string): string {
114 const separator = Math.max(path.lastIndexOf("/"), path.lastIndexOf("\\"));
115 return separator >= 0 ? path.slice(separator + 1) : path;
116}
117
118export function ComposerEditor({
119 ref,
120 skills = EMPTY_SKILLS,
121 selection,
122 style,
123 textStyle,
124 onChangeText,
125 onSelectionChange,
126 onPasteImages,
127 onPasteText,
128 onFocus,
129 onBlur,
130 onSubmit,
131 onContentSizeChange,
132 contentInsetVertical = 0,
133 ...props
134}: ComposerEditorProps) {
135 const nativeRef = useRef<NativeComposerEditorRef>(null);
136 const mostRecentEventCountRef = useRef(0);
137 const [mostRecentEventCount, setMostRecentEventCount] = useState(0);
138 const [, forceNativeEventRender] = useState(0);
139 // The native editor mounts empty, so the snapshot history starts empty: the
140 // first controlled payload must be a non-echo so a restored draft (or a
141 // recycled native view) is applied rather than skipped.
142 const nativeEventSnapshotsRef = useRef<ComposerNativeEventSnapshot[]>([]);
143 const confirmedTokensRef = useRef(collectComposerInlineTokens(props.value));
144 const bodyText = useScaledTextRole("body");
145 const theme = useUniwindTheme();
146 const fontFamily = FONT_FAMILIES.regular;
147
148 useImperativeHandle(
149 ref,
150 () => ({
151 focus: () => void nativeRef.current?.focus(),
152 blur: () => void nativeRef.current?.blur(),
153 setSelection: (nextSelection) =>
154 void nativeRef.current?.setSelection(nextSelection.start, nextSelection.end),
155 }),
156 [],
157 );
158
159 const skillLabels = useMemo(() => composerSkillLabels(skills), [skills]);
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: presentation.accent,
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]);
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 // A native event that arrived after this render was committed moves the
233 // acknowledged revision forward; the editor rejects this payload, so the
234 // snapshot history must not assume it applied.
235 if (isNativeEcho || controlledEventCount !== mostRecentEventCountRef.current) return;
236 nativeEventSnapshotsRef.current = assumeComposerControlledState(
237 nativeEventSnapshotsRef.current,
238 controlledEventCount,
239 assumedValue,
240 );
241 }, [assumedValue, controlledEventCount, isNativeEcho, controlledDocumentJson]);
242 const acceptNativeEvent = useCallback(
243 (eventCount: number, value: string, nextSelection: ComposerEditorSelection) => {
244 const acknowledgedEventCount = acknowledgeComposerNativeEvent(
245 mostRecentEventCountRef.current,
246 eventCount,
247 );
248 if (acknowledgedEventCount === null) {
249 return false;
250 }
251 mostRecentEventCountRef.current = acknowledgedEventCount;
252 nativeEventSnapshotsRef.current.push({
253 eventCount: acknowledgedEventCount,
254 value,
255 selection: nextSelection,
256 });
257 return acknowledgedEventCount;
258 },
259 [],
260 );
261 const themeJson = JSON.stringify(createNativeComposerTheme(theme));
262 const resolvedTextStyle = StyleSheet.flatten(textStyle) ?? {};
263 return (
264 <NativeView
265 ref={nativeRef}
266 controlledDocumentJson={controlledDocumentJson}
267 clipboardFragment={props.clipboardFragment ?? ""}
268 themeJson={themeJson}
269 placeholder={props.placeholder ?? ""}
270 fontFamily={
271 typeof resolvedTextStyle.fontFamily === "string" ? resolvedTextStyle.fontFamily : fontFamily
272 }
273 fontSize={
274 typeof resolvedTextStyle.fontSize === "number"
275 ? resolvedTextStyle.fontSize
276 : bodyText.fontSize
277 }
278 lineHeight={
279 typeof resolvedTextStyle.lineHeight === "number"
280 ? resolvedTextStyle.lineHeight
281 : bodyText.lineHeight
282 }
283 contentInsetVertical={contentInsetVertical}
284 editable={props.editable ?? true}
285 readOnly={props.readOnly ?? false}
286 enterBehavior={props.enterBehavior ?? DEFAULT_COMPOSER_ENTER_BEHAVIOR}
287 submitTitle={props.submitTitle ?? "Send Message"}
288 alternateSubmitTitle={props.alternateSubmitTitle ?? props.submitTitle ?? "Send Message"}
289 scrollEnabled={props.scrollEnabled ?? true}
290 autoFocus={props.autoFocus ?? false}
291 autoCorrect={props.autoCorrect ?? true}
292 spellCheck={props.spellCheck ?? true}
293 textPasteThresholdBytes={onPasteText ? PASTED_TEXT_ATTACHMENT_THRESHOLD_BYTES : 0}
294 maxInputChars={PROVIDER_SEND_TURN_MAX_INPUT_CHARS}
295 style={style as StyleProp<ViewStyle>}
296 onComposerChange={(event) => {
297 const acknowledgedEventCount = acceptNativeEvent(
298 event.nativeEvent.eventCount,
299 event.nativeEvent.value,
300 event.nativeEvent.selection,
301 );
302 if (acknowledgedEventCount === false) return;
303 onChangeText(event.nativeEvent.value);
304 onSelectionChange?.(event.nativeEvent.selection);
305 setMostRecentEventCount(acknowledgedEventCount);
306 forceNativeEventRender((sequence) => sequence + 1);
307 }}
308 onComposerSelectionChange={(event) => {
309 const acknowledgedEventCount = acceptNativeEvent(
310 event.nativeEvent.eventCount,
311 event.nativeEvent.value,
312 event.nativeEvent.selection,
313 );
314 if (acknowledgedEventCount === false) return;
315 // A selection change that raced a text mutation can carry post-edit
316 // text. It must reach the parent alongside the acknowledged revision,
317 // or the next render stamps the stale draft at that revision and can
318 // re-apply it over the newer native text.
319 if (event.nativeEvent.value !== props.value) {
320 onChangeText(event.nativeEvent.value);
321 }
322 onSelectionChange?.(event.nativeEvent.selection);
323 setMostRecentEventCount(acknowledgedEventCount);
324 forceNativeEventRender((sequence) => sequence + 1);
325 }}
326 onComposerPasteImages={(event) => onPasteImages?.(event.nativeEvent.uris)}
327 onComposerContextPress={(event) => props.onContextPress?.(event.nativeEvent)}
328 onComposerPasteContext={(event) => {
329 const paste = event.nativeEvent;
330 const acknowledgedEventCount = acceptNativeEvent(
331 paste.eventCount,
332 paste.value,
333 paste.selection,
334 );
335 if (acknowledgedEventCount === false) return;
336 onChangeText(paste.value);
337 onSelectionChange?.(paste.selection);
338 props.onPasteContext?.(paste);
339 setMostRecentEventCount(acknowledgedEventCount);
340 forceNativeEventRender((sequence) => sequence + 1);
341 }}
342 onComposerPasteText={(event) => {
343 const paste = event.nativeEvent;
344 const acknowledgedEventCount = acceptNativeEvent(
345 paste.eventCount,
346 paste.value,
347 paste.selection,
348 );
349 if (acknowledgedEventCount === false) return;
350 // Synchronize the draft before an async paste captures its insertion target.
351 // React props can still precede the last native keystroke.
352 onChangeText(paste.value);
353 onSelectionChange?.(paste.selection);
354 onPasteText?.(paste);
355 setMostRecentEventCount(acknowledgedEventCount);
356 forceNativeEventRender((sequence) => sequence + 1);
357 }}
358 onComposerFocus={onFocus}
359 onComposerBlur={onBlur}
360 onComposerContentSizeChange={
361 onContentSizeChange === undefined
362 ? undefined
363 : (event) => onContentSizeChange(event.nativeEvent)
364 }
365 onComposerSubmit={
366 onSubmit === undefined
367 ? undefined
368 : (event) => onSubmit(event.nativeEvent.alternate === true)
369 }
370 />
371 );
372}
373
374export type {
375 ComposerEditorHandle,
376 ComposerEditorProps,
377 ComposerEditorSelection,
378 ComposerTextPaste,
379} from "./T3ComposerEditor.types";