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 { StyleSheet } from "react-native";
17
18import {
19 markdownFileIconSource,
20 markdownIconAssetUri,
21} from "@t3tools/mobile-markdown-text/file-icons";
22import {
23 composerChipSizeSuffix,
24 contextChipPresentation,
25} from "@t3tools/mobile-markdown-text/markdown";
26import { resolveMarkdownFileIcon } from "@t3tools/mobile-markdown-text/links";
27import { useUniwindTheme } from "../lib/useUniwindTheme";
28import { createNativeComposerTheme } from "../lib/nativeComposerTheme";
29import { useFontFamily } from "../lib/useFontFamily";
30import { useScaledTextRole } from "../features/settings/appearance/useScaledTextRole";
31import {
32 acknowledgeComposerNativeEvent,
33 assumeComposerControlledState,
34 isComposerNativeEcho,
35 pruneAcknowledgedComposerNativeEvents,
36 resolveComposerControlledEventCount,
37 type ComposerNativeEventSnapshot,
38} from "./composerEditorRevision";
39import { DEFAULT_COMPOSER_ENTER_BEHAVIOR } from "../lib/composerEnterBehavior";
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 editable: boolean;
85 readonly readOnly: boolean;
86 readonly enterBehavior: string;
87 readonly submitTitle: string;
88 readonly alternateSubmitTitle: string;
89 readonly scrollEnabled: boolean;
90 readonly autoFocus: boolean;
91 readonly autoCorrect: boolean;
92 readonly spellCheck: boolean;
93 readonly onComposerChange: (event: NativeEditorEvent) => void;
94 readonly onComposerSelectionChange?: (event: NativeSelectionEvent) => void;
95 readonly onComposerPasteImages?: (event: NativePasteImagesEvent) => void;
96 readonly onComposerContextPress?: (
97 event: NativeSyntheticEvent<{ source: string; start: number; end: number }>,
98 ) => void;
99 readonly onComposerPasteContext?: (
100 event: NativePasteTextEvent & NativeSyntheticEvent<{ fragment: string; html: string }>,
101 ) => void;
102 readonly textPasteThresholdBytes: number;
103 readonly maxInputChars: number;
104 readonly onComposerPasteText?: (event: NativePasteTextEvent) => void;
105 readonly onComposerFocus?: () => void;
106 readonly onComposerBlur?: () => void;
107 readonly onComposerSubmit?: (event: NativeSyntheticEvent<{ alternate: boolean }>) => 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
117function fileIconUri(path: string): string | null {
118 return markdownIconAssetUri(markdownFileIconSource(resolveMarkdownFileIcon(path))) ?? null;
119}
120
121export function ComposerEditor({
122 ref,
123 skills = EMPTY_SKILLS,
124 selection,
125 style,
126 textStyle,
127 onChangeText,
128 onSelectionChange,
129 onPasteImages,
130 onPasteText,
131 onFocus,
132 onBlur,
133 onSubmit,
134 contentInsetVertical = 0,
135 ...props
136}: ComposerEditorProps) {
137 const nativeRef = useRef<NativeComposerEditorRef>(null);
138 const mostRecentEventCountRef = useRef(0);
139 const [mostRecentEventCount, setMostRecentEventCount] = useState(0);
140 const [, forceNativeEventRender] = useState(0);
141 // The native editor mounts empty, so the snapshot history starts empty: the
142 // first controlled payload must be a non-echo so a restored draft (or a
143 // recycled native view) is applied rather than skipped.
144 const nativeEventSnapshotsRef = useRef<ComposerNativeEventSnapshot[]>([]);
145 const confirmedTokensRef = useRef(collectComposerInlineTokens(props.value));
146 const bodyText = useScaledTextRole("body");
147 const theme = useUniwindTheme();
148 const fontFamily = useFontFamily("regular");
149
150 useImperativeHandle(
151 ref,
152 () => ({
153 focus: () => void nativeRef.current?.focus(),
154 blur: () => void nativeRef.current?.blur(),
155 setSelection: (nextSelection) =>
156 void nativeRef.current?.setSelection(nextSelection.start, nextSelection.end),
157 }),
158 [],
159 );
160
161 const skillLabels = useMemo(
162 () => new Map(skills.map((skill) => [skill.name, skill.displayName?.trim() || skill.name])),
163 [skills],
164 );
165 const tokensJson = useMemo(() => {
166 const tokens = collectComposerInlineTokens(props.value, {
167 preserveTrailingFrom: confirmedTokensRef.current,
168 });
169 confirmedTokensRef.current = tokens;
170 return JSON.stringify(
171 composerContextEditorTokens(props.value, tokens).map((token) => {
172 const record =
173 token.type === "context"
174 ? props.context?.records.find((record) => record.contextId === token.contextId)
175 : undefined;
176 return {
177 type: token.type,
178 source: token.source,
179 start: token.start,
180 end: token.end,
181 ...contextChipPresentation(token.type === "context" ? token.kind : token.type, record),
182 label:
183 token.type === "skill"
184 ? (skillLabels.get(token.value) ?? token.value)
185 : token.type === "context"
186 ? `${token.label}${props.context?.records.some((record) => record.contextId === token.contextId) ? "" : " · unavailable"}`
187 : basename(token.value),
188 detail: token.type === "context" ? composerChipSizeSuffix(record) : "",
189 // Only a mention wears per-filetype artwork. An attachment chip keeps the tinted
190 // monochrome glyph web draws for it: coloured artwork ignores the chip's accent and
191 // makes the composer chip read differently from the same chip in a sent message.
192 iconUri:
193 token.type === "mention"
194 ? fileIconUri(token.value)
195 : record?.kind === "mention" && "path" in record
196 ? fileIconUri(record.path)
197 : null,
198 };
199 }),
200 );
201 }, [props.value, props.context, skillLabels]);
202 // Every render resolves against the snapshot history, so a render whose
203 // (value, selection) lags the acknowledged native state is stamped behind
204 // the native revision and rejected by the editor instead of re-applying a
205 // stale caret or stale text mid-typing.
206 const controlledEventCount = resolveComposerControlledEventCount(
207 props.value,
208 selection ?? null,
209 mostRecentEventCount,
210 nativeEventSnapshotsRef.current,
211 );
212 const acknowledgesLatestNativeEvent = isComposerNativeEcho(
213 props.value,
214 selection ?? null,
215 mostRecentEventCount,
216 nativeEventSnapshotsRef.current,
217 );
218 const isNativeEcho =
219 controlledEventCount === mostRecentEventCount && acknowledgesLatestNativeEvent;
220 const controlledDocumentJson = JSON.stringify({
221 value: props.value,
222 selection: isNativeEcho ? null : (selection ?? null),
223 tokensJson,
224 mostRecentEventCount: controlledEventCount,
225 isNativeEcho,
226 });
227 useEffect(() => {
228 if (!acknowledgesLatestNativeEvent) return;
229 nativeEventSnapshotsRef.current = pruneAcknowledgedComposerNativeEvents(
230 nativeEventSnapshotsRef.current,
231 mostRecentEventCount,
232 );
233 }, [acknowledgesLatestNativeEvent, mostRecentEventCount]);
234 const assumedValue = props.value;
235 useEffect(() => {
236 // A native event that arrived after this render was committed moves the
237 // acknowledged revision forward; the editor rejects this payload, so the
238 // snapshot history must not assume it applied.
239 if (isNativeEcho || controlledEventCount !== mostRecentEventCountRef.current) return;
240 nativeEventSnapshotsRef.current = assumeComposerControlledState(
241 nativeEventSnapshotsRef.current,
242 controlledEventCount,
243 assumedValue,
244 );
245 }, [assumedValue, controlledEventCount, isNativeEcho, controlledDocumentJson]);
246 const acceptNativeEvent = useCallback(
247 (eventCount: number, value: string, nextSelection: ComposerEditorSelection) => {
248 const acknowledgedEventCount = acknowledgeComposerNativeEvent(
249 mostRecentEventCountRef.current,
250 eventCount,
251 );
252 if (acknowledgedEventCount === null) {
253 return false;
254 }
255 mostRecentEventCountRef.current = acknowledgedEventCount;
256 nativeEventSnapshotsRef.current.push({
257 eventCount: acknowledgedEventCount,
258 value,
259 selection: nextSelection,
260 });
261 return acknowledgedEventCount;
262 },
263 [],
264 );
265 const themeJson = JSON.stringify(createNativeComposerTheme(theme));
266 const resolvedTextStyle = StyleSheet.flatten(textStyle) ?? {};
267 return (
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" ? resolvedTextStyle.fontFamily : fontFamily
276 }
277 fontSize={
278 typeof resolvedTextStyle.fontSize === "number"
279 ? resolvedTextStyle.fontSize
280 : bodyText.fontSize
281 }
282 lineHeight={
283 typeof resolvedTextStyle.lineHeight === "number"
284 ? resolvedTextStyle.lineHeight
285 : bodyText.lineHeight
286 }
287 contentInsetVertical={contentInsetVertical}
288 editable={props.editable ?? true}
289 readOnly={props.readOnly ?? false}
290 enterBehavior={props.enterBehavior ?? DEFAULT_COMPOSER_ENTER_BEHAVIOR}
291 submitTitle={props.submitTitle ?? "Send Message"}
292 alternateSubmitTitle={props.alternateSubmitTitle ?? props.submitTitle ?? "Send Message"}
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={style as StyleProp<ViewStyle>}
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 // A selection change that raced a text mutation can carry post-edit
320 // text. It must reach the parent alongside the acknowledged revision,
321 // or the next render stamps the stale draft at that revision and can
322 // re-apply it over the newer native text.
323 if (event.nativeEvent.value !== props.value) {
324 onChangeText(event.nativeEvent.value);
325 }
326 onSelectionChange?.(event.nativeEvent.selection);
327 setMostRecentEventCount(acknowledgedEventCount);
328 forceNativeEventRender((sequence) => sequence + 1);
329 }}
330 onComposerPasteImages={(event) => onPasteImages?.(event.nativeEvent.uris)}
331 onComposerContextPress={(event) => props.onContextPress?.(event.nativeEvent)}
332 onComposerPasteContext={(event) => {
333 const paste = event.nativeEvent;
334 const acknowledgedEventCount = acceptNativeEvent(
335 paste.eventCount,
336 paste.value,
337 paste.selection,
338 );
339 if (acknowledgedEventCount === false) return;
340 onChangeText(paste.value);
341 onSelectionChange?.(paste.selection);
342 props.onPasteContext?.(paste);
343 setMostRecentEventCount(acknowledgedEventCount);
344 forceNativeEventRender((sequence) => sequence + 1);
345 }}
346 onComposerPasteText={(event) => {
347 const paste = event.nativeEvent;
348 const acknowledgedEventCount = acceptNativeEvent(
349 paste.eventCount,
350 paste.value,
351 paste.selection,
352 );
353 if (acknowledgedEventCount === false) return;
354 // Synchronize the draft before an async paste captures its insertion target.
355 // React props can still precede the last native keystroke.
356 onChangeText(paste.value);
357 onSelectionChange?.(paste.selection);
358 onPasteText?.(paste);
359 setMostRecentEventCount(acknowledgedEventCount);
360 forceNativeEventRender((sequence) => sequence + 1);
361 }}
362 onComposerFocus={onFocus}
363 onComposerBlur={onBlur}
364 onComposerSubmit={
365 onSubmit === undefined
366 ? undefined
367 : (event) => onSubmit(event.nativeEvent.alternate === true)
368 }
369 />
370 );
371}
372
373export type {
374 ComposerEditorHandle,
375 ComposerEditorProps,
376 ComposerEditorSelection,
377 ComposerTextPaste,
378} from "./T3ComposerEditor.types";