Open History to see the last commit
1import { collectComposerInlineTokens } from "@t3tools/shared/composerInlineTokens";
2import { composerContextEditorTokens } from "../lib/composerContext";
3import { requireNativeView } from "expo";
4import { TextInputWrapper } from "expo-paste-input";
5import {
6 useCallback,
7 useEffect,
8 useImperativeHandle,
9 useMemo,
10 useRef,
11 useState,
12 type Ref,
13} from "react";
14import type { NativeSyntheticEvent, ViewProps } from "react-native";
15import { Image, StyleSheet } from "react-native";
16
17import { markdownFileIconSource } from "@t3tools/mobile-markdown-text/file-icons";
18import {
19 composerChipSizeSuffix,
20 contextChipPresentation,
21} from "@t3tools/mobile-markdown-text/markdown";
22import { resolveMarkdownFileIcon } from "@t3tools/mobile-markdown-text/links";
23import { MOBILE_TYPOGRAPHY } from "../lib/typography";
24import { useNativePaste } from "../lib/useNativePaste";
25import { useFontFamily } from "../lib/useFontFamily";
26import { useAppearancePreferences } from "../features/settings/appearance/AppearancePreferencesProvider";
27import { useUniwindTheme } from "../lib/useUniwindTheme";
28import { flattenThemeColor } from "../lib/mobileTheme";
29import {
30 acknowledgeComposerNativeEvent,
31 assumeComposerControlledState,
32 isComposerNativeEcho,
33 pruneAcknowledgedComposerNativeEvents,
34 resolveComposerControlledEventCount,
35 type ComposerNativeEventSnapshot,
36} from "./composerEditorRevision";
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
58interface NativeComposerEditorRef {
59 focus: () => Promise<void>;
60 blur: () => Promise<void>;
61 setSelection: (start: number, end: number) => Promise<void>;
62}
63
64interface NativeComposerEditorProps extends ViewProps {
65 readonly ref?: Ref<NativeComposerEditorRef>;
66 readonly controlledDocumentJson: string;
67 readonly clipboardFragment: string;
68 readonly themeJson: string;
69 readonly placeholder: string;
70 readonly fontFamily: string;
71 readonly fontSize: number;
72 readonly lineHeight: number;
73 readonly contentInsetVertical: number;
74 readonly singleLineCentered: boolean;
75 readonly editable: boolean;
76 readonly readOnly: boolean;
77 readonly scrollEnabled: boolean;
78 readonly autoFocus: boolean;
79 readonly autoCorrect: boolean;
80 readonly spellCheck: boolean;
81 readonly onComposerChange: (event: NativeEditorEvent) => void;
82 readonly onComposerSelectionChange?: (event: NativeSelectionEvent) => void;
83 readonly onComposerPasteImages?: (event: NativePasteImagesEvent) => void;
84 readonly onComposerContextPress?: (
85 event: NativeSyntheticEvent<{ source: string; start: number; end: number }>,
86 ) => void;
87 readonly onComposerPasteContext?: (
88 event: NativeSyntheticEvent<{ text: string; fragment: string; html: string }>,
89 ) => void;
90 readonly onComposerFocus?: () => void;
91 readonly onComposerBlur?: () => void;
92}
93
94const NativeView = requireNativeView<NativeComposerEditorProps>(NATIVE_MODULE_NAME);
95
96function basename(path: string): string {
97 const separator = Math.max(path.lastIndexOf("/"), path.lastIndexOf("\\"));
98 return separator >= 0 ? path.slice(separator + 1) : path;
99}
100
101function fileIconUri(path: string): string {
102 return Image.resolveAssetSource(markdownFileIconSource(resolveMarkdownFileIcon(path))).uri;
103}
104
105export function ComposerEditor({
106 ref,
107 skills = EMPTY_SKILLS,
108 selection,
109 style,
110 textStyle,
111 onChangeText,
112 onSelectionChange,
113 onPasteImages,
114 onFocus,
115 onBlur,
116 contentInsetVertical = 0,
117 ...props
118}: ComposerEditorProps) {
119 const nativeRef = useRef<NativeComposerEditorRef>(null);
120 const mostRecentEventCountRef = useRef(0);
121 const [mostRecentEventCount, setMostRecentEventCount] = useState(0);
122 const [, forceNativeEventRender] = useState(0);
123 // The native editor mounts empty, so the snapshot history starts empty: the
124 // first controlled payload must be a non-echo so a restored draft (or a
125 // recycled native view) is applied rather than skipped.
126 const nativeEventSnapshotsRef = useRef<ComposerNativeEventSnapshot[]>([]);
127 const [initialConfirmedTokens] = useState(() => collectComposerInlineTokens(props.value));
128 const confirmedTokensRef = useRef(initialConfirmedTokens);
129 const theme = useUniwindTheme();
130 const handlePaste = useNativePaste((uris) => onPasteImages?.(uris));
131
132 useImperativeHandle(
133 ref,
134 () => ({
135 focus: () => void nativeRef.current?.focus(),
136 blur: () => void nativeRef.current?.blur(),
137 setSelection: (nextSelection) =>
138 void nativeRef.current?.setSelection(nextSelection.start, nextSelection.end),
139 }),
140 [],
141 );
142
143 const skillLabels = useMemo(
144 () => new Map(skills.map((skill) => [skill.name, skill.displayName?.trim() || skill.name])),
145 [skills],
146 );
147 const tokensJson = useMemo(() => {
148 const tokens = collectComposerInlineTokens(props.value, {
149 preserveTrailingFrom: confirmedTokensRef.current,
150 });
151 confirmedTokensRef.current = tokens;
152 return JSON.stringify(
153 composerContextEditorTokens(props.value, tokens).map((token) => {
154 const record =
155 token.type === "context"
156 ? props.context?.records.find((record) => record.contextId === token.contextId)
157 : undefined;
158 return {
159 type: token.type,
160 source: token.source,
161 start: token.start,
162 end: token.end,
163 ...contextChipPresentation(token.type === "context" ? token.kind : token.type, record),
164 label:
165 token.type === "skill"
166 ? (skillLabels.get(token.value) ?? token.value)
167 : token.type === "context"
168 ? `${token.label}${props.context?.records.some((record) => record.contextId === token.contextId) ? "" : " · unavailable"}`
169 : basename(token.value),
170 detail: token.type === "context" ? composerChipSizeSuffix(record) : "",
171 // Only a mention wears per-filetype artwork. An attachment chip keeps the tinted
172 // monochrome glyph web draws for it: coloured artwork ignores the chip's accent and
173 // makes the composer chip read differently from the same chip in a sent message.
174 iconUri:
175 token.type === "mention"
176 ? fileIconUri(token.value)
177 : record?.kind === "mention" && "path" in record
178 ? fileIconUri(record.path)
179 : null,
180 };
181 }),
182 );
183 }, [props.value, props.context, skillLabels]);
184 // Every render resolves against the snapshot history, so a render whose
185 // (value, selection) lags the acknowledged native state is stamped behind
186 // the native revision and rejected by the editor instead of re-applying a
187 // stale caret or stale text mid-typing.
188 const controlledEventCount = resolveComposerControlledEventCount(
189 props.value,
190 selection ?? null,
191 mostRecentEventCount,
192 nativeEventSnapshotsRef.current,
193 );
194 const acknowledgesLatestNativeEvent = isComposerNativeEcho(
195 props.value,
196 selection ?? null,
197 mostRecentEventCount,
198 nativeEventSnapshotsRef.current,
199 );
200 const isNativeEcho =
201 controlledEventCount === mostRecentEventCount && acknowledgesLatestNativeEvent;
202 const controlledDocumentJson = JSON.stringify({
203 value: props.value,
204 selection: isNativeEcho ? null : (selection ?? null),
205 tokensJson,
206 mostRecentEventCount: controlledEventCount,
207 isNativeEcho,
208 });
209 useEffect(() => {
210 if (!acknowledgesLatestNativeEvent) return;
211 nativeEventSnapshotsRef.current = pruneAcknowledgedComposerNativeEvents(
212 nativeEventSnapshotsRef.current,
213 mostRecentEventCount,
214 );
215 }, [acknowledgesLatestNativeEvent, mostRecentEventCount]);
216 const assumedValue = props.value;
217 useEffect(() => {
218 // A native event that arrived after this render was committed moves the
219 // acknowledged revision forward; the editor rejects this payload, so the
220 // snapshot history must not assume it applied.
221 if (isNativeEcho || controlledEventCount !== mostRecentEventCountRef.current) return;
222 nativeEventSnapshotsRef.current = assumeComposerControlledState(
223 nativeEventSnapshotsRef.current,
224 controlledEventCount,
225 assumedValue,
226 );
227 }, [assumedValue, controlledEventCount, isNativeEcho, controlledDocumentJson]);
228 const acceptNativeEvent = useCallback(
229 (eventCount: number, value: string, nextSelection: ComposerEditorSelection) => {
230 const acknowledgedEventCount = acknowledgeComposerNativeEvent(
231 mostRecentEventCountRef.current,
232 eventCount,
233 );
234 if (acknowledgedEventCount === null) {
235 return false;
236 }
237 mostRecentEventCountRef.current = acknowledgedEventCount;
238 nativeEventSnapshotsRef.current.push({
239 eventCount: acknowledgedEventCount,
240 value,
241 selection: nextSelection,
242 });
243 return acknowledgedEventCount;
244 },
245 [],
246 );
247 const { systemColorsActive } = useAppearancePreferences();
248 const themeJson = JSON.stringify({
249 selection: systemColorsActive ? theme["--color-primary"] : null,
250 text: theme["--color-foreground"],
251 placeholder: theme["--color-placeholder"],
252 chipBackground: theme["--color-subtle"],
253 // Native chip drawing parses opaque hex only, and this role is translucent.
254 chipBorder: flattenThemeColor(theme["--color-border"], theme["--color-user-bubble"]),
255 chipText: theme["--color-foreground"],
256 skillBackground: theme["--color-inline-skill-background"],
257 skillBorder: theme["--color-inline-skill-border"],
258 skillText: theme["--color-inline-skill-foreground"],
259 fileTint: theme["--color-icon-muted"],
260 });
261 const resolvedTextStyle = StyleSheet.flatten(textStyle) ?? {};
262 const regularFontFamily = useFontFamily("regular");
263 return (
264 <TextInputWrapper onPaste={handlePaste} style={[{ minHeight: 0 }, style]}>
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"
273 ? resolvedTextStyle.fontFamily
274 : regularFontFamily
275 }
276 fontSize={
277 typeof resolvedTextStyle.fontSize === "number"
278 ? resolvedTextStyle.fontSize
279 : MOBILE_TYPOGRAPHY.body.fontSize
280 }
281 lineHeight={
282 typeof resolvedTextStyle.lineHeight === "number"
283 ? resolvedTextStyle.lineHeight
284 : MOBILE_TYPOGRAPHY.body.lineHeight
285 }
286 contentInsetVertical={contentInsetVertical}
287 singleLineCentered={props.singleLineCentered ?? false}
288 editable={props.editable ?? true}
289 readOnly={props.readOnly ?? false}
290 scrollEnabled={props.scrollEnabled ?? true}
291 autoFocus={props.autoFocus ?? false}
292 autoCorrect={props.autoCorrect ?? true}
293 spellCheck={props.spellCheck ?? true}
294 style={{ flex: 1, minHeight: 0 }}
295 onComposerChange={(event) => {
296 const acknowledgedEventCount = acceptNativeEvent(
297 event.nativeEvent.eventCount,
298 event.nativeEvent.value,
299 event.nativeEvent.selection,
300 );
301 if (acknowledgedEventCount === false) return;
302 onChangeText(event.nativeEvent.value);
303 onSelectionChange?.(event.nativeEvent.selection);
304 setMostRecentEventCount(acknowledgedEventCount);
305 forceNativeEventRender((sequence) => sequence + 1);
306 }}
307 onComposerSelectionChange={(event) => {
308 const acknowledgedEventCount = acceptNativeEvent(
309 event.nativeEvent.eventCount,
310 event.nativeEvent.value,
311 event.nativeEvent.selection,
312 );
313 if (acknowledgedEventCount === false) return;
314 // Android emits the selection change mid-mutation, before the change
315 // event, so the payload can carry post-edit text. It must reach the
316 // parent alongside the acknowledged revision, or the next render
317 // stamps the stale draft at that revision and can re-apply it over
318 // the newer native text.
319 if (event.nativeEvent.value !== props.value) {
320 onChangeText(event.nativeEvent.value);
321 }
322 onSelectionChange?.(event.nativeEvent.selection);
323 setMostRecentEventCount(acknowledgedEventCount);
324 forceNativeEventRender((sequence) => sequence + 1);
325 }}
326 onComposerPasteImages={(event) => onPasteImages?.(event.nativeEvent.uris)}
327 onComposerContextPress={(event) => props.onContextPress?.(event.nativeEvent)}
328 onComposerPasteContext={(event) => props.onPasteContext?.(event.nativeEvent)}
329 onComposerFocus={onFocus}
330 onComposerBlur={onBlur}
331 />
332 </TextInputWrapper>
333 );
334}
335
336export type {
337 ComposerEditorHandle,
338 ComposerEditorProps,
339 ComposerEditorSelection,
340} from "./T3ComposerEditor.types";