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 // oxlint-disable-next-line t3code/no-unreasoned-state-sync -- prunes native editor event snapshots once a committed payload acknowledges them
238 useEffect(() => {
239 if (!acknowledgesLatestNativeEvent) return;
240 nativeEventSnapshotsRef.current = pruneAcknowledgedComposerNativeEvents(
241 nativeEventSnapshotsRef.current,
242 mostRecentEventCount,
243 );
244 }, [acknowledgesLatestNativeEvent, mostRecentEventCount, nativeEventSnapshotsRef]);
245 const assumedValue = props.value;
246 // oxlint-disable-next-line t3code/no-unreasoned-state-sync -- records the committed controlled payload as the native editor's assumed state
247 useEffect(() => {
248 // Newer native events make this payload stale; do not record it as applied.
249 if (isNativeEcho || controlledEventCount !== mostRecentEventCountRef.current) return;
250 nativeEventSnapshotsRef.current = assumeComposerControlledState(
251 nativeEventSnapshotsRef.current,
252 controlledEventCount,
253 assumedValue,
254 );
255 }, [
256 assumedValue,
257 controlledEventCount,
258 isNativeEcho,
259 // oxlint-disable-next-line react/exhaustive-effect-dependencies -- Every changed native payload, including selection-only changes, must update the assumed native snapshot.
260 controlledDocumentJson,
261 nativeEventSnapshotsRef,
262 ]);
263 const acceptNativeEvent = useCallback(
264 (eventCount: number, value: string, nextSelection: ComposerEditorSelection) => {
265 const acknowledgedEventCount = acknowledgeComposerNativeEvent(
266 mostRecentEventCountRef.current,
267 eventCount,
268 );
269 if (acknowledgedEventCount === null) {
270 return false;
271 }
272 mostRecentEventCountRef.current = acknowledgedEventCount;
273 nativeEventSnapshotsRef.current.push({
274 eventCount: acknowledgedEventCount,
275 value,
276 selection: nextSelection,
277 });
278 return acknowledgedEventCount;
279 },
280 [nativeEventSnapshotsRef],
281 );
282 const { systemColorsActive } = useAppearancePreferences();
283 const themeJson = JSON.stringify({
284 ...createNativeComposerTheme(theme),
285 selection: Platform.OS === "android" || systemColorsActive ? theme["--color-focus"] : null,
286 });
287 const resolvedTextStyle = StyleSheet.flatten(textStyle) ?? {};
288 const regularFontFamily = FONT_FAMILIES.regular;
289 return (
290 <TextInputWrapper onPaste={handlePaste} style={[{ minHeight: 0 }, style]}>
291 <NativeView
292 ref={nativeRef}
293 controlledDocumentJson={controlledDocumentJson}
294 clipboardFragment={props.clipboardFragment ?? ""}
295 themeJson={themeJson}
296 placeholder={props.placeholder ?? ""}
297 fontFamily={
298 typeof resolvedTextStyle.fontFamily === "string"
299 ? resolvedTextStyle.fontFamily
300 : regularFontFamily
301 }
302 fontSize={
303 typeof resolvedTextStyle.fontSize === "number"
304 ? resolvedTextStyle.fontSize
305 : MOBILE_TYPOGRAPHY.body.fontSize
306 }
307 lineHeight={
308 typeof resolvedTextStyle.lineHeight === "number"
309 ? resolvedTextStyle.lineHeight
310 : MOBILE_TYPOGRAPHY.body.lineHeight
311 }
312 contentInsetVertical={contentInsetVertical}
313 singleLineCentered={props.singleLineCentered ?? false}
314 editable={props.editable ?? true}
315 readOnly={props.readOnly ?? false}
316 scrollEnabled={props.scrollEnabled ?? true}
317 autoFocus={props.autoFocus ?? false}
318 autoCorrect={props.autoCorrect ?? true}
319 spellCheck={props.spellCheck ?? true}
320 textPasteThresholdBytes={onPasteText ? PASTED_TEXT_ATTACHMENT_THRESHOLD_BYTES : 0}
321 maxInputChars={PROVIDER_SEND_TURN_MAX_INPUT_CHARS}
322 style={{ flex: 1, minHeight: 0 }}
323 onComposerChange={(event) => {
324 const acknowledgedEventCount = acceptNativeEvent(
325 event.nativeEvent.eventCount,
326 event.nativeEvent.value,
327 event.nativeEvent.selection,
328 );
329 if (acknowledgedEventCount === false) return;
330 onChangeText(event.nativeEvent.value);
331 onSelectionChange?.(event.nativeEvent.selection);
332 setMostRecentEventCount(acknowledgedEventCount);
333 forceNativeEventRender((sequence) => sequence + 1);
334 }}
335 onComposerSelectionChange={(event) => {
336 const acknowledgedEventCount = acceptNativeEvent(
337 event.nativeEvent.eventCount,
338 event.nativeEvent.value,
339 event.nativeEvent.selection,
340 );
341 if (acknowledgedEventCount === false) return;
342 // Android selection events may precede text changes; publish text and revision together to reject stale drafts.
343 if (event.nativeEvent.value !== props.value) {
344 onChangeText(event.nativeEvent.value);
345 }
346 onSelectionChange?.(event.nativeEvent.selection);
347 setMostRecentEventCount(acknowledgedEventCount);
348 forceNativeEventRender((sequence) => sequence + 1);
349 }}
350 onComposerPasteImages={(event) => onPasteImages?.(event.nativeEvent.uris)}
351 onComposerContextPress={(event) => props.onContextPress?.(event.nativeEvent)}
352 onComposerPasteContext={(event) => {
353 const paste = event.nativeEvent;
354 const acknowledgedEventCount = acceptNativeEvent(
355 paste.eventCount,
356 paste.value,
357 paste.selection,
358 );
359 if (acknowledgedEventCount === false) return;
360 onChangeText(paste.value);
361 onSelectionChange?.(paste.selection);
362 props.onPasteContext?.(paste);
363 setMostRecentEventCount(acknowledgedEventCount);
364 forceNativeEventRender((sequence) => sequence + 1);
365 }}
366 onComposerPasteText={(event) => {
367 const paste = event.nativeEvent;
368 const acknowledgedEventCount = acceptNativeEvent(
369 paste.eventCount,
370 paste.value,
371 paste.selection,
372 );
373 if (acknowledgedEventCount === false) return;
374 // Sync before capturing async paste targets; props may lag the last native keystroke.
375 onChangeText(paste.value);
376 onSelectionChange?.(paste.selection);
377 onPasteText?.(paste);
378 setMostRecentEventCount(acknowledgedEventCount);
379 forceNativeEventRender((sequence) => sequence + 1);
380 }}
381 onComposerFocus={onFocus}
382 onComposerBlur={onBlur}
383 onComposerContentSizeChange={
384 onContentSizeChange === undefined
385 ? undefined
386 : (event) => onContentSizeChange(event.nativeEvent)
387 }
388 />
389 </TextInputWrapper>
390 );
391}
392
393export type {
394 ComposerEditorHandle,
395 ComposerEditorProps,
396 ComposerEditorSelection,
397 ComposerTextPaste,
398} from "./T3ComposerEditor.types";