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