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