Open History to see the last commit
1import { collectComposerInlineTokens } from "@t3tools/shared/composerInlineTokens";
2import { requireNativeView } from "expo";
3import { TextInputWrapper } from "expo-paste-input";
4import {
5 useCallback,
6 useEffect,
7 useImperativeHandle,
8 useMemo,
9 useRef,
10 useState,
11 type Ref,
12} from "react";
13import type { NativeSyntheticEvent, ViewProps } from "react-native";
14import { Image, StyleSheet } from "react-native";
15
16import { markdownFileIconSource } from "@t3tools/mobile-markdown-text/file-icons";
17import { resolveMarkdownFileIcon } from "@t3tools/mobile-markdown-text/links";
18import { MOBILE_TYPOGRAPHY } from "../lib/typography";
19import { useNativePaste } from "../lib/useNativePaste";
20import { useFontFamily } from "../lib/useFontFamily";
21import { useUniwindTheme } from "../lib/useUniwindTheme";
22import {
23 acknowledgeComposerNativeEvent,
24 assumeComposerControlledState,
25 isComposerNativeEcho,
26 pruneAcknowledgedComposerNativeEvents,
27 resolveComposerControlledEventCount,
28 type ComposerNativeEventSnapshot,
29} from "./composerEditorRevision";
30import type { ComposerEditorProps, ComposerEditorSelection } from "./T3ComposerEditor.types";
31
32const NATIVE_MODULE_NAME = "T3ComposerEditor";
33const EMPTY_SKILLS: NonNullable<ComposerEditorProps["skills"]> = [];
34
35type NativeEditorEvent = NativeSyntheticEvent<{
36 readonly value: string;
37 readonly selection: ComposerEditorSelection;
38 readonly eventCount: number;
39}>;
40
41type NativeSelectionEvent = NativeSyntheticEvent<{
42 readonly value: string;
43 readonly selection: ComposerEditorSelection;
44 readonly eventCount: number;
45}>;
46
47type NativePasteImagesEvent = NativeSyntheticEvent<{
48 readonly uris: ReadonlyArray<string>;
49}>;
50
51interface NativeComposerEditorRef {
52 focus: () => Promise<void>;
53 blur: () => Promise<void>;
54 setSelection: (start: number, end: number) => Promise<void>;
55}
56
57interface NativeComposerEditorProps extends ViewProps {
58 readonly ref?: Ref<NativeComposerEditorRef>;
59 readonly controlledDocumentJson: string;
60 readonly themeJson: string;
61 readonly placeholder: string;
62 readonly fontFamily: string;
63 readonly fontSize: number;
64 readonly lineHeight: number;
65 readonly contentInsetVertical: number;
66 readonly singleLineCentered: boolean;
67 readonly editable: boolean;
68 readonly scrollEnabled: boolean;
69 readonly autoFocus: boolean;
70 readonly autoCorrect: boolean;
71 readonly spellCheck: boolean;
72 readonly onComposerChange: (event: NativeEditorEvent) => void;
73 readonly onComposerSelectionChange?: (event: NativeSelectionEvent) => void;
74 readonly onComposerPasteImages?: (event: NativePasteImagesEvent) => void;
75 readonly onComposerFocus?: () => void;
76 readonly onComposerBlur?: () => void;
77}
78
79const NativeView = requireNativeView<NativeComposerEditorProps>(NATIVE_MODULE_NAME);
80
81function basename(path: string): string {
82 const separator = Math.max(path.lastIndexOf("/"), path.lastIndexOf("\\"));
83 return separator >= 0 ? path.slice(separator + 1) : path;
84}
85
86function fileIconUri(path: string): string {
87 return Image.resolveAssetSource(markdownFileIconSource(resolveMarkdownFileIcon(path))).uri;
88}
89
90export function ComposerEditor({
91 ref,
92 skills = EMPTY_SKILLS,
93 selection,
94 style,
95 textStyle,
96 onChangeText,
97 onSelectionChange,
98 onPasteImages,
99 onFocus,
100 onBlur,
101 contentInsetVertical = 0,
102 ...props
103}: ComposerEditorProps) {
104 const nativeRef = useRef<NativeComposerEditorRef>(null);
105 const mostRecentEventCountRef = useRef(0);
106 const [mostRecentEventCount, setMostRecentEventCount] = useState(0);
107 const [, forceNativeEventRender] = useState(0);
108 // The native editor mounts empty, so the snapshot history starts empty: the
109 // first controlled payload must be a non-echo so a restored draft (or a
110 // recycled native view) is applied rather than skipped.
111 const nativeEventSnapshotsRef = useRef<ComposerNativeEventSnapshot[]>([]);
112 const [initialConfirmedTokens] = useState(() => collectComposerInlineTokens(props.value));
113 const confirmedTokensRef = useRef(initialConfirmedTokens);
114 const theme = useUniwindTheme();
115 const handlePaste = useNativePaste((uris) => onPasteImages?.(uris));
116
117 useImperativeHandle(
118 ref,
119 () => ({
120 focus: () => void nativeRef.current?.focus(),
121 blur: () => void nativeRef.current?.blur(),
122 setSelection: (nextSelection) =>
123 void nativeRef.current?.setSelection(nextSelection.start, nextSelection.end),
124 }),
125 [],
126 );
127
128 const skillLabels = useMemo(
129 () => new Map(skills.map((skill) => [skill.name, skill.displayName?.trim() || skill.name])),
130 [skills],
131 );
132 const tokensJson = useMemo(() => {
133 const tokens = collectComposerInlineTokens(props.value, {
134 preserveTrailingFrom: confirmedTokensRef.current,
135 });
136 confirmedTokensRef.current = tokens;
137 return JSON.stringify(
138 tokens.map((token) => ({
139 type: token.type,
140 source: token.source,
141 start: token.start,
142 end: token.end,
143 label:
144 token.type === "skill"
145 ? (skillLabels.get(token.value) ?? token.value)
146 : basename(token.value),
147 iconUri: token.type === "mention" ? fileIconUri(token.value) : null,
148 })),
149 );
150 }, [props.value, skillLabels]);
151 // Every render resolves against the snapshot history, so a render whose
152 // (value, selection) lags the acknowledged native state is stamped behind
153 // the native revision and rejected by the editor instead of re-applying a
154 // stale caret or stale text mid-typing.
155 const controlledEventCount = resolveComposerControlledEventCount(
156 props.value,
157 selection ?? null,
158 mostRecentEventCount,
159 nativeEventSnapshotsRef.current,
160 );
161 const acknowledgesLatestNativeEvent = isComposerNativeEcho(
162 props.value,
163 selection ?? null,
164 mostRecentEventCount,
165 nativeEventSnapshotsRef.current,
166 );
167 const isNativeEcho =
168 controlledEventCount === mostRecentEventCount && acknowledgesLatestNativeEvent;
169 const controlledDocumentJson = JSON.stringify({
170 value: props.value,
171 selection: isNativeEcho ? null : (selection ?? null),
172 tokensJson,
173 mostRecentEventCount: controlledEventCount,
174 isNativeEcho,
175 });
176 useEffect(() => {
177 if (!acknowledgesLatestNativeEvent) return;
178 nativeEventSnapshotsRef.current = pruneAcknowledgedComposerNativeEvents(
179 nativeEventSnapshotsRef.current,
180 mostRecentEventCount,
181 );
182 }, [acknowledgesLatestNativeEvent, mostRecentEventCount]);
183 const assumedValue = props.value;
184 useEffect(() => {
185 // A native event that arrived after this render was committed moves the
186 // acknowledged revision forward; the editor rejects this payload, so the
187 // snapshot history must not assume it applied.
188 if (isNativeEcho || controlledEventCount !== mostRecentEventCountRef.current) return;
189 nativeEventSnapshotsRef.current = assumeComposerControlledState(
190 nativeEventSnapshotsRef.current,
191 controlledEventCount,
192 assumedValue,
193 );
194 }, [assumedValue, controlledEventCount, isNativeEcho, controlledDocumentJson]);
195 const acceptNativeEvent = useCallback(
196 (eventCount: number, value: string, nextSelection: ComposerEditorSelection) => {
197 const acknowledgedEventCount = acknowledgeComposerNativeEvent(
198 mostRecentEventCountRef.current,
199 eventCount,
200 );
201 if (acknowledgedEventCount === null) {
202 return false;
203 }
204 mostRecentEventCountRef.current = acknowledgedEventCount;
205 nativeEventSnapshotsRef.current.push({
206 eventCount: acknowledgedEventCount,
207 value,
208 selection: nextSelection,
209 });
210 return acknowledgedEventCount;
211 },
212 [],
213 );
214 const themeJson = JSON.stringify({
215 text: theme["--color-foreground"],
216 placeholder: theme["--color-placeholder"],
217 chipBackground: theme["--color-subtle"],
218 chipBorder: theme["--color-border"],
219 chipText: theme["--color-foreground"],
220 skillBackground: theme["--color-inline-skill-background"],
221 skillBorder: theme["--color-inline-skill-border"],
222 skillText: theme["--color-inline-skill-foreground"],
223 fileTint: theme["--color-icon-muted"],
224 });
225 const resolvedTextStyle = StyleSheet.flatten(textStyle) ?? {};
226 const regularFontFamily = useFontFamily("regular");
227 return (
228 <TextInputWrapper onPaste={handlePaste} style={[{ minHeight: 0 }, style]}>
229 <NativeView
230 ref={nativeRef}
231 controlledDocumentJson={controlledDocumentJson}
232 themeJson={themeJson}
233 placeholder={props.placeholder ?? ""}
234 fontFamily={
235 typeof resolvedTextStyle.fontFamily === "string"
236 ? resolvedTextStyle.fontFamily
237 : regularFontFamily
238 }
239 fontSize={
240 typeof resolvedTextStyle.fontSize === "number"
241 ? resolvedTextStyle.fontSize
242 : MOBILE_TYPOGRAPHY.body.fontSize
243 }
244 lineHeight={
245 typeof resolvedTextStyle.lineHeight === "number"
246 ? resolvedTextStyle.lineHeight
247 : MOBILE_TYPOGRAPHY.body.lineHeight
248 }
249 contentInsetVertical={contentInsetVertical}
250 singleLineCentered={props.singleLineCentered ?? false}
251 editable={(props.editable ?? true) && !(props.readOnly ?? false)}
252 scrollEnabled={props.scrollEnabled ?? true}
253 autoFocus={props.autoFocus ?? false}
254 autoCorrect={props.autoCorrect ?? true}
255 spellCheck={props.spellCheck ?? true}
256 style={{ flex: 1, minHeight: 0 }}
257 onComposerChange={(event) => {
258 const acknowledgedEventCount = acceptNativeEvent(
259 event.nativeEvent.eventCount,
260 event.nativeEvent.value,
261 event.nativeEvent.selection,
262 );
263 if (acknowledgedEventCount === false) return;
264 onChangeText(event.nativeEvent.value);
265 onSelectionChange?.(event.nativeEvent.selection);
266 setMostRecentEventCount(acknowledgedEventCount);
267 forceNativeEventRender((sequence) => sequence + 1);
268 }}
269 onComposerSelectionChange={(event) => {
270 const acknowledgedEventCount = acceptNativeEvent(
271 event.nativeEvent.eventCount,
272 event.nativeEvent.value,
273 event.nativeEvent.selection,
274 );
275 if (acknowledgedEventCount === false) return;
276 // Android emits the selection change mid-mutation, before the change
277 // event, so the payload can carry post-edit text. It must reach the
278 // parent alongside the acknowledged revision, or the next render
279 // stamps the stale draft at that revision and can re-apply it over
280 // the newer native text.
281 if (event.nativeEvent.value !== props.value) {
282 onChangeText(event.nativeEvent.value);
283 }
284 onSelectionChange?.(event.nativeEvent.selection);
285 setMostRecentEventCount(acknowledgedEventCount);
286 forceNativeEventRender((sequence) => sequence + 1);
287 }}
288 onComposerPasteImages={(event) => onPasteImages?.(event.nativeEvent.uris)}
289 onComposerFocus={onFocus}
290 onComposerBlur={onBlur}
291 />
292 </TextInputWrapper>
293 );
294}
295
296export type {
297 ComposerEditorHandle,
298 ComposerEditorProps,
299 ComposerEditorSelection,
300} from "./T3ComposerEditor.types";