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 { Image, 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
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 onContentSizeChange,
131 contentInsetVertical = 0,
132 ...props
133}: ComposerEditorProps) {
134 const nativeRef = useRef<NativeComposerEditorRef>(null);
135 const mostRecentEventCountRef = useRef(0);
136 const [mostRecentEventCount, setMostRecentEventCount] = useState(0);
137 const [, forceNativeEventRender] = useState(0);
138 // Start history empty so restored drafts or recycled views receive a non-echo controlled payload.
139 const nativeEventSnapshotsRef = useRef<ComposerNativeEventSnapshot[]>([]);
140 const [initialConfirmedTokens] = useState(() => collectComposerInlineTokens(props.value));
141 const confirmedTokensRef = useRef(initialConfirmedTokens);
142 const theme = useUniwindTheme();
143 const handlePaste = useNativePaste((uris) => onPasteImages?.(uris));
144
145 useImperativeHandle(
146 ref,
147 () => ({
148 focus: () => void nativeRef.current?.focus(),
149 blur: () => void nativeRef.current?.blur(),
150 setSelection: (nextSelection) =>
151 void nativeRef.current?.setSelection(nextSelection.start, nextSelection.end),
152 }),
153 [],
154 );
155
156 const skillLabels = useMemo(() => composerSkillLabels(skills), [skills]);
157 const chipTextColor = createNativeComposerTheme(theme).text;
158 const tokensJson = useMemo(() => {
159 const tokens = collectComposerInlineTokens(props.value, {
160 preserveTrailingFrom: confirmedTokensRef.current,
161 });
162 confirmedTokensRef.current = tokens;
163 return JSON.stringify(
164 composerContextEditorTokens(props.value, tokens, skillLabels).map((token) => {
165 const record =
166 token.type === "context"
167 ? props.context?.records.find((record) => record.contextId === token.contextId)
168 : undefined;
169 const presentation = contextChipPresentation(
170 token.type === "context" ? token.kind : token.type,
171 record,
172 );
173 const icon = contextChipIcon(
174 presentation,
175 token.type === "mention" ? token.value : contextRecordFileName(record),
176 );
177 return {
178 type: token.type,
179 source: token.source,
180 start: token.start,
181 end: token.end,
182 accent: contextChipAccent(presentation.accent, theme, chipTextColor),
183 label:
184 token.type === "skill"
185 ? (skillLabels.get(token.value) ?? token.value)
186 : token.type === "context"
187 ? `${token.label}${props.context?.records.some((record) => record.contextId === token.contextId) ? "" : " · unavailable"}`
188 : basename(token.value),
189 detail: token.type === "context" ? composerChipSizeSuffix(record) : "",
190 iconUri: contextChipIconUri(icon),
191 tintsIcon: icon.kind === "chip",
192 };
193 }),
194 );
195 }, [props.value, props.context, skillLabels, theme, chipTextColor]);
196 // Every render resolves against the snapshot history, so a render whose
197 // (value, selection) lags the acknowledged native state is stamped behind
198 // the native revision and rejected by the editor instead of re-applying a
199 // stale caret or stale text mid-typing.
200 const controlledEventCount = resolveComposerControlledEventCount(
201 props.value,
202 selection ?? null,
203 mostRecentEventCount,
204 nativeEventSnapshotsRef.current,
205 );
206 const acknowledgesLatestNativeEvent = isComposerNativeEcho(
207 props.value,
208 selection ?? null,
209 mostRecentEventCount,
210 nativeEventSnapshotsRef.current,
211 );
212 const isNativeEcho =
213 controlledEventCount === mostRecentEventCount && acknowledgesLatestNativeEvent;
214 const controlledDocumentJson = JSON.stringify({
215 value: props.value,
216 selection: isNativeEcho ? null : (selection ?? null),
217 tokensJson,
218 mostRecentEventCount: controlledEventCount,
219 isNativeEcho,
220 });
221 useEffect(() => {
222 if (!acknowledgesLatestNativeEvent) return;
223 nativeEventSnapshotsRef.current = pruneAcknowledgedComposerNativeEvents(
224 nativeEventSnapshotsRef.current,
225 mostRecentEventCount,
226 );
227 }, [acknowledgesLatestNativeEvent, mostRecentEventCount]);
228 const assumedValue = props.value;
229 useEffect(() => {
230 // Newer native events make this payload stale; do not record it as applied.
231 if (isNativeEcho || controlledEventCount !== mostRecentEventCountRef.current) return;
232 nativeEventSnapshotsRef.current = assumeComposerControlledState(
233 nativeEventSnapshotsRef.current,
234 controlledEventCount,
235 assumedValue,
236 );
237 }, [assumedValue, controlledEventCount, isNativeEcho, controlledDocumentJson]);
238 const acceptNativeEvent = useCallback(
239 (eventCount: number, value: string, nextSelection: ComposerEditorSelection) => {
240 const acknowledgedEventCount = acknowledgeComposerNativeEvent(
241 mostRecentEventCountRef.current,
242 eventCount,
243 );
244 if (acknowledgedEventCount === null) {
245 return false;
246 }
247 mostRecentEventCountRef.current = acknowledgedEventCount;
248 nativeEventSnapshotsRef.current.push({
249 eventCount: acknowledgedEventCount,
250 value,
251 selection: nextSelection,
252 });
253 return acknowledgedEventCount;
254 },
255 [],
256 );
257 const { systemColorsActive } = useAppearancePreferences();
258 const themeJson = JSON.stringify({
259 ...createNativeComposerTheme(theme),
260 selection: Platform.OS === "android" || systemColorsActive ? theme["--color-focus"] : null,
261 });
262 const resolvedTextStyle = StyleSheet.flatten(textStyle) ?? {};
263 const regularFontFamily = FONT_FAMILIES.regular;
264 return (
265 <TextInputWrapper onPaste={handlePaste} style={[{ minHeight: 0 }, style]}>
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"
274 ? resolvedTextStyle.fontFamily
275 : regularFontFamily
276 }
277 fontSize={
278 typeof resolvedTextStyle.fontSize === "number"
279 ? resolvedTextStyle.fontSize
280 : MOBILE_TYPOGRAPHY.body.fontSize
281 }
282 lineHeight={
283 typeof resolvedTextStyle.lineHeight === "number"
284 ? resolvedTextStyle.lineHeight
285 : MOBILE_TYPOGRAPHY.body.lineHeight
286 }
287 contentInsetVertical={contentInsetVertical}
288 singleLineCentered={props.singleLineCentered ?? false}
289 editable={props.editable ?? true}
290 readOnly={props.readOnly ?? false}
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={{ flex: 1, minHeight: 0 }}
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 // Android selection events may precede text changes; publish text and revision together to reject stale drafts.
318 if (event.nativeEvent.value !== props.value) {
319 onChangeText(event.nativeEvent.value);
320 }
321 onSelectionChange?.(event.nativeEvent.selection);
322 setMostRecentEventCount(acknowledgedEventCount);
323 forceNativeEventRender((sequence) => sequence + 1);
324 }}
325 onComposerPasteImages={(event) => onPasteImages?.(event.nativeEvent.uris)}
326 onComposerContextPress={(event) => props.onContextPress?.(event.nativeEvent)}
327 onComposerPasteContext={(event) => {
328 const paste = event.nativeEvent;
329 const acknowledgedEventCount = acceptNativeEvent(
330 paste.eventCount,
331 paste.value,
332 paste.selection,
333 );
334 if (acknowledgedEventCount === false) return;
335 onChangeText(paste.value);
336 onSelectionChange?.(paste.selection);
337 props.onPasteContext?.(paste);
338 setMostRecentEventCount(acknowledgedEventCount);
339 forceNativeEventRender((sequence) => sequence + 1);
340 }}
341 onComposerPasteText={(event) => {
342 const paste = event.nativeEvent;
343 const acknowledgedEventCount = acceptNativeEvent(
344 paste.eventCount,
345 paste.value,
346 paste.selection,
347 );
348 if (acknowledgedEventCount === false) return;
349 // Sync before capturing async paste targets; props may lag the last native keystroke.
350 onChangeText(paste.value);
351 onSelectionChange?.(paste.selection);
352 onPasteText?.(paste);
353 setMostRecentEventCount(acknowledgedEventCount);
354 forceNativeEventRender((sequence) => sequence + 1);
355 }}
356 onComposerFocus={onFocus}
357 onComposerBlur={onBlur}
358 onComposerContentSizeChange={
359 onContentSizeChange === undefined
360 ? undefined
361 : (event) => onContentSizeChange(event.nativeEvent)
362 }
363 />
364 </TextInputWrapper>
365 );
366}
367
368export type {
369 ComposerEditorHandle,
370 ComposerEditorProps,
371 ComposerEditorSelection,
372 ComposerTextPaste,
373} from "./T3ComposerEditor.types";