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 } from "../lib/composerContext";
5import { requireNativeView } from "expo";
6import {
7 useCallback,
8 useEffect,
9 useImperativeHandle,
10 useMemo,
11 useRef,
12 useState,
13 type Ref,
14} from "react";
15import type { NativeSyntheticEvent, StyleProp, ViewProps, ViewStyle } from "react-native";
16import { Image, StyleSheet } from "react-native";
17
18import { markdownFileIconSource } from "@t3tools/mobile-markdown-text/file-icons";
19import {
20 composerChipSizeSuffix,
21 contextChipPresentation,
22} from "@t3tools/mobile-markdown-text/markdown";
23import { resolveMarkdownFileIcon } from "@t3tools/mobile-markdown-text/links";
24import { useUniwindTheme } from "../lib/useUniwindTheme";
25import { createNativeComposerTheme } from "../lib/nativeComposerTheme";
26import { useFontFamily } from "../lib/useFontFamily";
27import { useScaledTextRole } from "../features/settings/appearance/useScaledTextRole";
28import {
29 acknowledgeComposerNativeEvent,
30 assumeComposerControlledState,
31 isComposerNativeEcho,
32 pruneAcknowledgedComposerNativeEvents,
33 resolveComposerControlledEventCount,
34 type ComposerNativeEventSnapshot,
35} from "./composerEditorRevision";
36import { DEFAULT_COMPOSER_ENTER_BEHAVIOR } from "../lib/composerEnterBehavior";
37import type { ComposerEditorProps, ComposerEditorSelection } from "./T3ComposerEditor.types";
38
39const NATIVE_MODULE_NAME = "T3ComposerEditor";
40const EMPTY_SKILLS: NonNullable<ComposerEditorProps["skills"]> = [];
41
42type NativeEditorEvent = NativeSyntheticEvent<{
43 readonly value: string;
44 readonly selection: ComposerEditorSelection;
45 readonly eventCount: number;
46}>;
47
48type NativeSelectionEvent = NativeSyntheticEvent<{
49 readonly value: string;
50 readonly selection: ComposerEditorSelection;
51 readonly eventCount: number;
52}>;
53
54type NativePasteImagesEvent = NativeSyntheticEvent<{
55 readonly uris: ReadonlyArray<string>;
56}>;
57
58type NativePasteTextEvent = NativeSyntheticEvent<{
59 readonly value: string;
60 readonly eventCount: number;
61 readonly text: string;
62 readonly selection: ComposerEditorSelection;
63}>;
64
65interface NativeComposerEditorRef {
66 focus: () => Promise<void>;
67 blur: () => Promise<void>;
68 setSelection: (start: number, end: number) => Promise<void>;
69}
70
71interface NativeComposerEditorProps extends ViewProps {
72 readonly ref?: Ref<NativeComposerEditorRef>;
73 readonly controlledDocumentJson: string;
74 readonly clipboardFragment: string;
75 readonly themeJson: string;
76 readonly placeholder: string;
77 readonly fontFamily: string;
78 readonly fontSize: number;
79 readonly lineHeight: number;
80 readonly contentInsetVertical: number;
81 readonly editable: boolean;
82 readonly readOnly: boolean;
83 readonly enterBehavior: string;
84 readonly submitTitle: string;
85 readonly alternateSubmitTitle: string;
86 readonly scrollEnabled: boolean;
87 readonly autoFocus: boolean;
88 readonly autoCorrect: boolean;
89 readonly spellCheck: boolean;
90 readonly onComposerChange: (event: NativeEditorEvent) => void;
91 readonly onComposerSelectionChange?: (event: NativeSelectionEvent) => void;
92 readonly onComposerPasteImages?: (event: NativePasteImagesEvent) => void;
93 readonly onComposerContextPress?: (
94 event: NativeSyntheticEvent<{ source: string; start: number; end: number }>,
95 ) => void;
96 readonly onComposerPasteContext?: (
97 event: NativePasteTextEvent & NativeSyntheticEvent<{ fragment: string; html: string }>,
98 ) => void;
99 readonly textPasteThresholdBytes: number;
100 readonly maxInputChars: number;
101 readonly onComposerPasteText?: (event: NativePasteTextEvent) => void;
102 readonly onComposerFocus?: () => void;
103 readonly onComposerBlur?: () => void;
104 readonly onComposerSubmit?: (event: NativeSyntheticEvent<{ alternate: boolean }>) => void;
105}
106
107const NativeView = requireNativeView<NativeComposerEditorProps>(NATIVE_MODULE_NAME);
108
109function basename(path: string): string {
110 const separator = Math.max(path.lastIndexOf("/"), path.lastIndexOf("\\"));
111 return separator >= 0 ? path.slice(separator + 1) : path;
112}
113
114function fileIconUri(path: string): string {
115 return Image.resolveAssetSource(markdownFileIconSource(resolveMarkdownFileIcon(path))).uri;
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 onSubmit,
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 confirmedTokensRef = useRef(collectComposerInlineTokens(props.value));
143 const bodyText = useScaledTextRole("body");
144 const theme = useUniwindTheme();
145 const fontFamily = useFontFamily("regular");
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(
159 () => new Map(skills.map((skill) => [skill.name, skill.displayName?.trim() || skill.name])),
160 [skills],
161 );
162 const tokensJson = useMemo(() => {
163 const tokens = collectComposerInlineTokens(props.value, {
164 preserveTrailingFrom: confirmedTokensRef.current,
165 });
166 confirmedTokensRef.current = tokens;
167 return JSON.stringify(
168 composerContextEditorTokens(props.value, tokens).map((token) => {
169 const record =
170 token.type === "context"
171 ? props.context?.records.find((record) => record.contextId === token.contextId)
172 : undefined;
173 return {
174 type: token.type,
175 source: token.source,
176 start: token.start,
177 end: token.end,
178 ...contextChipPresentation(token.type === "context" ? token.kind : token.type, record),
179 label:
180 token.type === "skill"
181 ? (skillLabels.get(token.value) ?? token.value)
182 : token.type === "context"
183 ? `${token.label}${props.context?.records.some((record) => record.contextId === token.contextId) ? "" : " · unavailable"}`
184 : basename(token.value),
185 detail: token.type === "context" ? composerChipSizeSuffix(record) : "",
186 // Only a mention wears per-filetype artwork. An attachment chip keeps the tinted
187 // monochrome glyph web draws for it: coloured artwork ignores the chip's accent and
188 // makes the composer chip read differently from the same chip in a sent message.
189 iconUri:
190 token.type === "mention"
191 ? fileIconUri(token.value)
192 : record?.kind === "mention" && "path" in record
193 ? fileIconUri(record.path)
194 : null,
195 };
196 }),
197 );
198 }, [props.value, props.context, skillLabels]);
199 // Every render resolves against the snapshot history, so a render whose
200 // (value, selection) lags the acknowledged native state is stamped behind
201 // the native revision and rejected by the editor instead of re-applying a
202 // stale caret or stale text mid-typing.
203 const controlledEventCount = resolveComposerControlledEventCount(
204 props.value,
205 selection ?? null,
206 mostRecentEventCount,
207 nativeEventSnapshotsRef.current,
208 );
209 const acknowledgesLatestNativeEvent = isComposerNativeEcho(
210 props.value,
211 selection ?? null,
212 mostRecentEventCount,
213 nativeEventSnapshotsRef.current,
214 );
215 const isNativeEcho =
216 controlledEventCount === mostRecentEventCount && acknowledgesLatestNativeEvent;
217 const controlledDocumentJson = JSON.stringify({
218 value: props.value,
219 selection: isNativeEcho ? null : (selection ?? null),
220 tokensJson,
221 mostRecentEventCount: controlledEventCount,
222 isNativeEcho,
223 });
224 useEffect(() => {
225 if (!acknowledgesLatestNativeEvent) return;
226 nativeEventSnapshotsRef.current = pruneAcknowledgedComposerNativeEvents(
227 nativeEventSnapshotsRef.current,
228 mostRecentEventCount,
229 );
230 }, [acknowledgesLatestNativeEvent, mostRecentEventCount]);
231 const assumedValue = props.value;
232 useEffect(() => {
233 // A native event that arrived after this render was committed moves the
234 // acknowledged revision forward; the editor rejects this payload, so the
235 // snapshot history must not assume it applied.
236 if (isNativeEcho || controlledEventCount !== mostRecentEventCountRef.current) return;
237 nativeEventSnapshotsRef.current = assumeComposerControlledState(
238 nativeEventSnapshotsRef.current,
239 controlledEventCount,
240 assumedValue,
241 );
242 }, [assumedValue, controlledEventCount, isNativeEcho, controlledDocumentJson]);
243 const acceptNativeEvent = useCallback(
244 (eventCount: number, value: string, nextSelection: ComposerEditorSelection) => {
245 const acknowledgedEventCount = acknowledgeComposerNativeEvent(
246 mostRecentEventCountRef.current,
247 eventCount,
248 );
249 if (acknowledgedEventCount === null) {
250 return false;
251 }
252 mostRecentEventCountRef.current = acknowledgedEventCount;
253 nativeEventSnapshotsRef.current.push({
254 eventCount: acknowledgedEventCount,
255 value,
256 selection: nextSelection,
257 });
258 return acknowledgedEventCount;
259 },
260 [],
261 );
262 const themeJson = JSON.stringify(createNativeComposerTheme(theme));
263 const resolvedTextStyle = StyleSheet.flatten(textStyle) ?? {};
264 return (
265 <NativeView
266 ref={nativeRef}
267 controlledDocumentJson={controlledDocumentJson}
268 clipboardFragment={props.clipboardFragment ?? ""}
269 themeJson={themeJson}
270 placeholder={props.placeholder ?? ""}
271 fontFamily={
272 typeof resolvedTextStyle.fontFamily === "string" ? resolvedTextStyle.fontFamily : fontFamily
273 }
274 fontSize={
275 typeof resolvedTextStyle.fontSize === "number"
276 ? resolvedTextStyle.fontSize
277 : bodyText.fontSize
278 }
279 lineHeight={
280 typeof resolvedTextStyle.lineHeight === "number"
281 ? resolvedTextStyle.lineHeight
282 : bodyText.lineHeight
283 }
284 contentInsetVertical={contentInsetVertical}
285 editable={props.editable ?? true}
286 readOnly={props.readOnly ?? false}
287 enterBehavior={props.enterBehavior ?? DEFAULT_COMPOSER_ENTER_BEHAVIOR}
288 submitTitle={props.submitTitle ?? "Send Message"}
289 alternateSubmitTitle={props.alternateSubmitTitle ?? props.submitTitle ?? "Send Message"}
290 scrollEnabled={props.scrollEnabled ?? true}
291 autoFocus={props.autoFocus ?? false}
292 autoCorrect={props.autoCorrect ?? true}
293 spellCheck={props.spellCheck ?? true}
294 textPasteThresholdBytes={onPasteText ? PASTED_TEXT_ATTACHMENT_THRESHOLD_BYTES : 0}
295 maxInputChars={PROVIDER_SEND_TURN_MAX_INPUT_CHARS}
296 style={style as StyleProp<ViewStyle>}
297 onComposerChange={(event) => {
298 const acknowledgedEventCount = acceptNativeEvent(
299 event.nativeEvent.eventCount,
300 event.nativeEvent.value,
301 event.nativeEvent.selection,
302 );
303 if (acknowledgedEventCount === false) return;
304 onChangeText(event.nativeEvent.value);
305 onSelectionChange?.(event.nativeEvent.selection);
306 setMostRecentEventCount(acknowledgedEventCount);
307 forceNativeEventRender((sequence) => sequence + 1);
308 }}
309 onComposerSelectionChange={(event) => {
310 const acknowledgedEventCount = acceptNativeEvent(
311 event.nativeEvent.eventCount,
312 event.nativeEvent.value,
313 event.nativeEvent.selection,
314 );
315 if (acknowledgedEventCount === false) return;
316 // A selection change that raced a text mutation can carry post-edit
317 // text. It must reach the parent alongside the acknowledged revision,
318 // or the next render stamps the stale draft at that revision and can
319 // re-apply it over the newer native text.
320 if (event.nativeEvent.value !== props.value) {
321 onChangeText(event.nativeEvent.value);
322 }
323 onSelectionChange?.(event.nativeEvent.selection);
324 setMostRecentEventCount(acknowledgedEventCount);
325 forceNativeEventRender((sequence) => sequence + 1);
326 }}
327 onComposerPasteImages={(event) => onPasteImages?.(event.nativeEvent.uris)}
328 onComposerContextPress={(event) => props.onContextPress?.(event.nativeEvent)}
329 onComposerPasteContext={(event) => {
330 const paste = event.nativeEvent;
331 const acknowledgedEventCount = acceptNativeEvent(
332 paste.eventCount,
333 paste.value,
334 paste.selection,
335 );
336 if (acknowledgedEventCount === false) return;
337 onChangeText(paste.value);
338 onSelectionChange?.(paste.selection);
339 props.onPasteContext?.(paste);
340 setMostRecentEventCount(acknowledgedEventCount);
341 forceNativeEventRender((sequence) => sequence + 1);
342 }}
343 onComposerPasteText={(event) => {
344 const paste = event.nativeEvent;
345 const acknowledgedEventCount = acceptNativeEvent(
346 paste.eventCount,
347 paste.value,
348 paste.selection,
349 );
350 if (acknowledgedEventCount === false) return;
351 // Synchronize the draft before an async paste captures its insertion target.
352 // React props can still precede the last native keystroke.
353 onChangeText(paste.value);
354 onSelectionChange?.(paste.selection);
355 onPasteText?.(paste);
356 setMostRecentEventCount(acknowledgedEventCount);
357 forceNativeEventRender((sequence) => sequence + 1);
358 }}
359 onComposerFocus={onFocus}
360 onComposerBlur={onBlur}
361 onComposerSubmit={
362 onSubmit === undefined
363 ? undefined
364 : (event) => onSubmit(event.nativeEvent.alternate === true)
365 }
366 />
367 );
368}
369
370export type {
371 ComposerEditorHandle,
372 ComposerEditorProps,
373 ComposerEditorSelection,
374 ComposerTextPaste,
375} from "./T3ComposerEditor.types";