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 // The native editor mounts empty, so the snapshot history starts empty: the
139 // first controlled payload must be a non-echo so a restored draft (or a
140 // recycled native view) is applied rather than skipped.
141 const nativeEventSnapshotsRef = useRef<ComposerNativeEventSnapshot[]>([]);
142 const [initialConfirmedTokens] = useState(() => collectComposerInlineTokens(props.value));
143 const confirmedTokensRef = useRef(initialConfirmedTokens);
144 const theme = useUniwindTheme();
145 const handlePaste = useNativePaste((uris) => onPasteImages?.(uris));
146
147 useImperativeHandle(
148 ref,
149 () => ({
150 focus: () => void nativeRef.current?.focus(),
151 blur: () => void nativeRef.current?.blur(),
152 setSelection: (nextSelection) =>
153 void nativeRef.current?.setSelection(nextSelection.start, nextSelection.end),
154 }),
155 [],
156 );
157
158 const skillLabels = useMemo(() => composerSkillLabels(skills), [skills]);
159 const chipTextColor = createNativeComposerTheme(theme).text;
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: contextChipAccent(presentation.accent, theme, chipTextColor),
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, theme, chipTextColor]);
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 { systemColorsActive } = useAppearancePreferences();
262 const themeJson = JSON.stringify({
263 ...createNativeComposerTheme(theme),
264 selection: Platform.OS === "android" || systemColorsActive ? theme["--color-focus"] : null,
265 });
266 const resolvedTextStyle = StyleSheet.flatten(textStyle) ?? {};
267 const regularFontFamily = FONT_FAMILIES.regular;
268 return (
269 <TextInputWrapper onPaste={handlePaste} style={[{ minHeight: 0 }, style]}>
270 <NativeView
271 ref={nativeRef}
272 controlledDocumentJson={controlledDocumentJson}
273 clipboardFragment={props.clipboardFragment ?? ""}
274 themeJson={themeJson}
275 placeholder={props.placeholder ?? ""}
276 fontFamily={
277 typeof resolvedTextStyle.fontFamily === "string"
278 ? resolvedTextStyle.fontFamily
279 : regularFontFamily
280 }
281 fontSize={
282 typeof resolvedTextStyle.fontSize === "number"
283 ? resolvedTextStyle.fontSize
284 : MOBILE_TYPOGRAPHY.body.fontSize
285 }
286 lineHeight={
287 typeof resolvedTextStyle.lineHeight === "number"
288 ? resolvedTextStyle.lineHeight
289 : MOBILE_TYPOGRAPHY.body.lineHeight
290 }
291 contentInsetVertical={contentInsetVertical}
292 singleLineCentered={props.singleLineCentered ?? false}
293 editable={props.editable ?? true}
294 readOnly={props.readOnly ?? false}
295 scrollEnabled={props.scrollEnabled ?? true}
296 autoFocus={props.autoFocus ?? false}
297 autoCorrect={props.autoCorrect ?? true}
298 spellCheck={props.spellCheck ?? true}
299 textPasteThresholdBytes={onPasteText ? PASTED_TEXT_ATTACHMENT_THRESHOLD_BYTES : 0}
300 maxInputChars={PROVIDER_SEND_TURN_MAX_INPUT_CHARS}
301 style={{ flex: 1, minHeight: 0 }}
302 onComposerChange={(event) => {
303 const acknowledgedEventCount = acceptNativeEvent(
304 event.nativeEvent.eventCount,
305 event.nativeEvent.value,
306 event.nativeEvent.selection,
307 );
308 if (acknowledgedEventCount === false) return;
309 onChangeText(event.nativeEvent.value);
310 onSelectionChange?.(event.nativeEvent.selection);
311 setMostRecentEventCount(acknowledgedEventCount);
312 forceNativeEventRender((sequence) => sequence + 1);
313 }}
314 onComposerSelectionChange={(event) => {
315 const acknowledgedEventCount = acceptNativeEvent(
316 event.nativeEvent.eventCount,
317 event.nativeEvent.value,
318 event.nativeEvent.selection,
319 );
320 if (acknowledgedEventCount === false) return;
321 // Android emits the selection change mid-mutation, before the change
322 // event, so the payload can carry post-edit text. It must reach the
323 // parent alongside the acknowledged revision, or the next render
324 // stamps the stale draft at that revision and can re-apply it over
325 // the newer native text.
326 if (event.nativeEvent.value !== props.value) {
327 onChangeText(event.nativeEvent.value);
328 }
329 onSelectionChange?.(event.nativeEvent.selection);
330 setMostRecentEventCount(acknowledgedEventCount);
331 forceNativeEventRender((sequence) => sequence + 1);
332 }}
333 onComposerPasteImages={(event) => onPasteImages?.(event.nativeEvent.uris)}
334 onComposerContextPress={(event) => props.onContextPress?.(event.nativeEvent)}
335 onComposerPasteContext={(event) => {
336 const paste = event.nativeEvent;
337 const acknowledgedEventCount = acceptNativeEvent(
338 paste.eventCount,
339 paste.value,
340 paste.selection,
341 );
342 if (acknowledgedEventCount === false) return;
343 onChangeText(paste.value);
344 onSelectionChange?.(paste.selection);
345 props.onPasteContext?.(paste);
346 setMostRecentEventCount(acknowledgedEventCount);
347 forceNativeEventRender((sequence) => sequence + 1);
348 }}
349 onComposerPasteText={(event) => {
350 const paste = event.nativeEvent;
351 const acknowledgedEventCount = acceptNativeEvent(
352 paste.eventCount,
353 paste.value,
354 paste.selection,
355 );
356 if (acknowledgedEventCount === false) return;
357 // Synchronize the draft before an async paste captures its insertion target.
358 // React props can still precede the last native keystroke.
359 onChangeText(paste.value);
360 onSelectionChange?.(paste.selection);
361 onPasteText?.(paste);
362 setMostRecentEventCount(acknowledgedEventCount);
363 forceNativeEventRender((sequence) => sequence + 1);
364 }}
365 onComposerFocus={onFocus}
366 onComposerBlur={onBlur}
367 onComposerContentSizeChange={
368 onContentSizeChange === undefined
369 ? undefined
370 : (event) => onContentSizeChange(event.nativeEvent)
371 }
372 />
373 </TextInputWrapper>
374 );
375}
376
377export type {
378 ComposerEditorHandle,
379 ComposerEditorProps,
380 ComposerEditorSelection,
381 ComposerTextPaste,
382} from "./T3ComposerEditor.types";