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 { flattenThemeColor } from "../lib/mobileTheme";
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 scrollEnabled: boolean;
85 readonly autoFocus: boolean;
86 readonly autoCorrect: boolean;
87 readonly spellCheck: boolean;
88 readonly onComposerChange: (event: NativeEditorEvent) => void;
89 readonly onComposerSelectionChange?: (event: NativeSelectionEvent) => void;
90 readonly onComposerPasteImages?: (event: NativePasteImagesEvent) => void;
91 readonly onComposerContextPress?: (
92 event: NativeSyntheticEvent<{ source: string; start: number; end: number }>,
93 ) => void;
94 readonly onComposerPasteContext?: (
95 event: NativePasteTextEvent & NativeSyntheticEvent<{ fragment: string; html: string }>,
96 ) => void;
97 readonly textPasteThresholdBytes: number;
98 readonly maxInputChars: number;
99 readonly onComposerPasteText?: (event: NativePasteTextEvent) => void;
100 readonly onComposerFocus?: () => void;
101 readonly onComposerBlur?: () => void;
102 readonly onComposerSubmit?: () => void;
103}
104
105const NativeView = requireNativeView<NativeComposerEditorProps>(NATIVE_MODULE_NAME);
106
107function basename(path: string): string {
108 const separator = Math.max(path.lastIndexOf("/"), path.lastIndexOf("\\"));
109 return separator >= 0 ? path.slice(separator + 1) : path;
110}
111
112function fileIconUri(path: string): string {
113 return Image.resolveAssetSource(markdownFileIconSource(resolveMarkdownFileIcon(path))).uri;
114}
115
116export function ComposerEditor({
117 ref,
118 skills = EMPTY_SKILLS,
119 selection,
120 style,
121 textStyle,
122 onChangeText,
123 onSelectionChange,
124 onPasteImages,
125 onPasteText,
126 onFocus,
127 onBlur,
128 onSubmit,
129 contentInsetVertical = 0,
130 ...props
131}: ComposerEditorProps) {
132 const nativeRef = useRef<NativeComposerEditorRef>(null);
133 const mostRecentEventCountRef = useRef(0);
134 const [mostRecentEventCount, setMostRecentEventCount] = useState(0);
135 const [, forceNativeEventRender] = useState(0);
136 // The native editor mounts empty, so the snapshot history starts empty: the
137 // first controlled payload must be a non-echo so a restored draft (or a
138 // recycled native view) is applied rather than skipped.
139 const nativeEventSnapshotsRef = useRef<ComposerNativeEventSnapshot[]>([]);
140 const confirmedTokensRef = useRef(collectComposerInlineTokens(props.value));
141 const bodyText = useScaledTextRole("body");
142 const theme = useUniwindTheme();
143 const fontFamily = useFontFamily("regular");
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(
157 () => new Map(skills.map((skill) => [skill.name, skill.displayName?.trim() || skill.name])),
158 [skills],
159 );
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).map((token) => {
167 const record =
168 token.type === "context"
169 ? props.context?.records.find((record) => record.contextId === token.contextId)
170 : undefined;
171 return {
172 type: token.type,
173 source: token.source,
174 start: token.start,
175 end: token.end,
176 ...contextChipPresentation(token.type === "context" ? token.kind : token.type, record),
177 label:
178 token.type === "skill"
179 ? (skillLabels.get(token.value) ?? token.value)
180 : token.type === "context"
181 ? `${token.label}${props.context?.records.some((record) => record.contextId === token.contextId) ? "" : " · unavailable"}`
182 : basename(token.value),
183 detail: token.type === "context" ? composerChipSizeSuffix(record) : "",
184 // Only a mention wears per-filetype artwork. An attachment chip keeps the tinted
185 // monochrome glyph web draws for it: coloured artwork ignores the chip's accent and
186 // makes the composer chip read differently from the same chip in a sent message.
187 iconUri:
188 token.type === "mention"
189 ? fileIconUri(token.value)
190 : record?.kind === "mention" && "path" in record
191 ? fileIconUri(record.path)
192 : null,
193 };
194 }),
195 );
196 }, [props.value, props.context, skillLabels]);
197 // Every render resolves against the snapshot history, so a render whose
198 // (value, selection) lags the acknowledged native state is stamped behind
199 // the native revision and rejected by the editor instead of re-applying a
200 // stale caret or stale text mid-typing.
201 const controlledEventCount = resolveComposerControlledEventCount(
202 props.value,
203 selection ?? null,
204 mostRecentEventCount,
205 nativeEventSnapshotsRef.current,
206 );
207 const acknowledgesLatestNativeEvent = isComposerNativeEcho(
208 props.value,
209 selection ?? null,
210 mostRecentEventCount,
211 nativeEventSnapshotsRef.current,
212 );
213 const isNativeEcho =
214 controlledEventCount === mostRecentEventCount && acknowledgesLatestNativeEvent;
215 const controlledDocumentJson = JSON.stringify({
216 value: props.value,
217 selection: isNativeEcho ? null : (selection ?? null),
218 tokensJson,
219 mostRecentEventCount: controlledEventCount,
220 isNativeEcho,
221 });
222 useEffect(() => {
223 if (!acknowledgesLatestNativeEvent) return;
224 nativeEventSnapshotsRef.current = pruneAcknowledgedComposerNativeEvents(
225 nativeEventSnapshotsRef.current,
226 mostRecentEventCount,
227 );
228 }, [acknowledgesLatestNativeEvent, mostRecentEventCount]);
229 const assumedValue = props.value;
230 useEffect(() => {
231 // A native event that arrived after this render was committed moves the
232 // acknowledged revision forward; the editor rejects this payload, so the
233 // snapshot history must not assume it applied.
234 if (isNativeEcho || controlledEventCount !== mostRecentEventCountRef.current) return;
235 nativeEventSnapshotsRef.current = assumeComposerControlledState(
236 nativeEventSnapshotsRef.current,
237 controlledEventCount,
238 assumedValue,
239 );
240 }, [assumedValue, controlledEventCount, isNativeEcho, controlledDocumentJson]);
241 const acceptNativeEvent = useCallback(
242 (eventCount: number, value: string, nextSelection: ComposerEditorSelection) => {
243 const acknowledgedEventCount = acknowledgeComposerNativeEvent(
244 mostRecentEventCountRef.current,
245 eventCount,
246 );
247 if (acknowledgedEventCount === null) {
248 return false;
249 }
250 mostRecentEventCountRef.current = acknowledgedEventCount;
251 nativeEventSnapshotsRef.current.push({
252 eventCount: acknowledgedEventCount,
253 value,
254 selection: nextSelection,
255 });
256 return acknowledgedEventCount;
257 },
258 [],
259 );
260 const themeJson = JSON.stringify({
261 text: theme["--color-foreground"],
262 placeholder: theme["--color-placeholder"],
263 chipBackground: theme["--color-subtle"],
264 // Native chip drawing parses opaque hex only, and this role is translucent.
265 chipBorder: flattenThemeColor(theme["--color-border"], theme["--color-user-bubble"]),
266 chipText: theme["--color-foreground"],
267 skillBackground: theme["--color-inline-skill-background"],
268 skillBorder: theme["--color-inline-skill-border"],
269 skillText: theme["--color-inline-skill-foreground"],
270 fileTint: theme["--color-icon-muted"],
271 });
272 const resolvedTextStyle = StyleSheet.flatten(textStyle) ?? {};
273 return (
274 <NativeView
275 ref={nativeRef}
276 controlledDocumentJson={controlledDocumentJson}
277 clipboardFragment={props.clipboardFragment ?? ""}
278 themeJson={themeJson}
279 placeholder={props.placeholder ?? ""}
280 fontFamily={
281 typeof resolvedTextStyle.fontFamily === "string" ? resolvedTextStyle.fontFamily : fontFamily
282 }
283 fontSize={
284 typeof resolvedTextStyle.fontSize === "number"
285 ? resolvedTextStyle.fontSize
286 : bodyText.fontSize
287 }
288 lineHeight={
289 typeof resolvedTextStyle.lineHeight === "number"
290 ? resolvedTextStyle.lineHeight
291 : bodyText.lineHeight
292 }
293 contentInsetVertical={contentInsetVertical}
294 editable={props.editable ?? true}
295 readOnly={props.readOnly ?? false}
296 enterBehavior={props.enterBehavior ?? DEFAULT_COMPOSER_ENTER_BEHAVIOR}
297 scrollEnabled={props.scrollEnabled ?? true}
298 autoFocus={props.autoFocus ?? false}
299 autoCorrect={props.autoCorrect ?? true}
300 spellCheck={props.spellCheck ?? true}
301 textPasteThresholdBytes={onPasteText ? PASTED_TEXT_ATTACHMENT_THRESHOLD_BYTES : 0}
302 maxInputChars={PROVIDER_SEND_TURN_MAX_INPUT_CHARS}
303 style={style as StyleProp<ViewStyle>}
304 onComposerChange={(event) => {
305 const acknowledgedEventCount = acceptNativeEvent(
306 event.nativeEvent.eventCount,
307 event.nativeEvent.value,
308 event.nativeEvent.selection,
309 );
310 if (acknowledgedEventCount === false) return;
311 onChangeText(event.nativeEvent.value);
312 onSelectionChange?.(event.nativeEvent.selection);
313 setMostRecentEventCount(acknowledgedEventCount);
314 forceNativeEventRender((sequence) => sequence + 1);
315 }}
316 onComposerSelectionChange={(event) => {
317 const acknowledgedEventCount = acceptNativeEvent(
318 event.nativeEvent.eventCount,
319 event.nativeEvent.value,
320 event.nativeEvent.selection,
321 );
322 if (acknowledgedEventCount === false) return;
323 // A selection change that raced a text mutation can carry post-edit
324 // text. It must reach the parent alongside the acknowledged revision,
325 // or the next render stamps the stale draft at that revision and can
326 // re-apply it over the newer native text.
327 if (event.nativeEvent.value !== props.value) {
328 onChangeText(event.nativeEvent.value);
329 }
330 onSelectionChange?.(event.nativeEvent.selection);
331 setMostRecentEventCount(acknowledgedEventCount);
332 forceNativeEventRender((sequence) => sequence + 1);
333 }}
334 onComposerPasteImages={(event) => onPasteImages?.(event.nativeEvent.uris)}
335 onComposerContextPress={(event) => props.onContextPress?.(event.nativeEvent)}
336 onComposerPasteContext={(event) => {
337 const paste = event.nativeEvent;
338 const acknowledgedEventCount = acceptNativeEvent(
339 paste.eventCount,
340 paste.value,
341 paste.selection,
342 );
343 if (acknowledgedEventCount === false) return;
344 onChangeText(paste.value);
345 onSelectionChange?.(paste.selection);
346 props.onPasteContext?.(paste);
347 setMostRecentEventCount(acknowledgedEventCount);
348 forceNativeEventRender((sequence) => sequence + 1);
349 }}
350 onComposerPasteText={(event) => {
351 const paste = event.nativeEvent;
352 const acknowledgedEventCount = acceptNativeEvent(
353 paste.eventCount,
354 paste.value,
355 paste.selection,
356 );
357 if (acknowledgedEventCount === false) return;
358 // Synchronize the draft before an async paste captures its insertion target.
359 // React props can still precede the last native keystroke.
360 onChangeText(paste.value);
361 onSelectionChange?.(paste.selection);
362 onPasteText?.(paste);
363 setMostRecentEventCount(acknowledgedEventCount);
364 forceNativeEventRender((sequence) => sequence + 1);
365 }}
366 onComposerFocus={onFocus}
367 onComposerBlur={onBlur}
368 onComposerSubmit={onSubmit}
369 />
370 );
371}
372
373export type {
374 ComposerEditorHandle,
375 ComposerEditorProps,
376 ComposerEditorSelection,
377 ComposerTextPaste,
378} from "./T3ComposerEditor.types";