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 { useThemeColor } from "../lib/useThemeColor";
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 textColor = useThemeColor("--color-foreground");
115 const placeholderColor = useThemeColor("--color-placeholder");
116 const chipBackground = useThemeColor("--color-subtle");
117 const chipBorder = useThemeColor("--color-border");
118 const chipText = useThemeColor("--color-foreground");
119 const skillBackground = useThemeColor("--color-inline-skill-background");
120 const skillBorder = useThemeColor("--color-inline-skill-border");
121 const skillText = useThemeColor("--color-inline-skill-foreground");
122 const fileTint = useThemeColor("--color-icon-muted");
123 const handlePaste = useNativePaste((uris) => onPasteImages?.(uris));
124
125 useImperativeHandle(
126 ref,
127 () => ({
128 focus: () => void nativeRef.current?.focus(),
129 blur: () => void nativeRef.current?.blur(),
130 setSelection: (nextSelection) =>
131 void nativeRef.current?.setSelection(nextSelection.start, nextSelection.end),
132 }),
133 [],
134 );
135
136 const skillLabels = useMemo(
137 () => new Map(skills.map((skill) => [skill.name, skill.displayName?.trim() || skill.name])),
138 [skills],
139 );
140 const tokensJson = useMemo(() => {
141 const tokens = collectComposerInlineTokens(props.value, {
142 preserveTrailingFrom: confirmedTokensRef.current,
143 });
144 confirmedTokensRef.current = tokens;
145 return JSON.stringify(
146 tokens.map((token) => ({
147 type: token.type,
148 source: token.source,
149 start: token.start,
150 end: token.end,
151 label:
152 token.type === "skill"
153 ? (skillLabels.get(token.value) ?? token.value)
154 : basename(token.value),
155 iconUri: token.type === "mention" ? fileIconUri(token.value) : null,
156 })),
157 );
158 }, [props.value, skillLabels]);
159 // Every render resolves against the snapshot history, so a render whose
160 // (value, selection) lags the acknowledged native state is stamped behind
161 // the native revision and rejected by the editor instead of re-applying a
162 // stale caret or stale text mid-typing.
163 const controlledEventCount = resolveComposerControlledEventCount(
164 props.value,
165 selection ?? null,
166 mostRecentEventCount,
167 nativeEventSnapshotsRef.current,
168 );
169 const acknowledgesLatestNativeEvent = isComposerNativeEcho(
170 props.value,
171 selection ?? null,
172 mostRecentEventCount,
173 nativeEventSnapshotsRef.current,
174 );
175 const isNativeEcho =
176 controlledEventCount === mostRecentEventCount && acknowledgesLatestNativeEvent;
177 const controlledDocumentJson = JSON.stringify({
178 value: props.value,
179 selection: isNativeEcho ? null : (selection ?? null),
180 tokensJson,
181 mostRecentEventCount: controlledEventCount,
182 isNativeEcho,
183 });
184 useEffect(() => {
185 if (!acknowledgesLatestNativeEvent) return;
186 nativeEventSnapshotsRef.current = pruneAcknowledgedComposerNativeEvents(
187 nativeEventSnapshotsRef.current,
188 mostRecentEventCount,
189 );
190 }, [acknowledgesLatestNativeEvent, mostRecentEventCount]);
191 const assumedValue = props.value;
192 useEffect(() => {
193 // A native event that arrived after this render was committed moves the
194 // acknowledged revision forward; the editor rejects this payload, so the
195 // snapshot history must not assume it applied.
196 if (isNativeEcho || controlledEventCount !== mostRecentEventCountRef.current) return;
197 nativeEventSnapshotsRef.current = assumeComposerControlledState(
198 nativeEventSnapshotsRef.current,
199 controlledEventCount,
200 assumedValue,
201 );
202 }, [assumedValue, controlledEventCount, isNativeEcho, controlledDocumentJson]);
203 const acceptNativeEvent = useCallback(
204 (eventCount: number, value: string, nextSelection: ComposerEditorSelection) => {
205 const acknowledgedEventCount = acknowledgeComposerNativeEvent(
206 mostRecentEventCountRef.current,
207 eventCount,
208 );
209 if (acknowledgedEventCount === null) {
210 return false;
211 }
212 mostRecentEventCountRef.current = acknowledgedEventCount;
213 nativeEventSnapshotsRef.current.push({
214 eventCount: acknowledgedEventCount,
215 value,
216 selection: nextSelection,
217 });
218 return acknowledgedEventCount;
219 },
220 [],
221 );
222 const themeJson = JSON.stringify({
223 text: String(textColor),
224 placeholder: String(placeholderColor),
225 chipBackground: String(chipBackground),
226 chipBorder: String(chipBorder),
227 chipText: String(chipText),
228 skillBackground: String(skillBackground),
229 skillBorder: String(skillBorder),
230 skillText: String(skillText),
231 fileTint: String(fileTint),
232 });
233 const resolvedTextStyle = StyleSheet.flatten(textStyle) ?? {};
234 const regularFontFamily = useFontFamily("regular");
235 return (
236 <TextInputWrapper onPaste={handlePaste} style={[{ minHeight: 0 }, style]}>
237 <NativeView
238 ref={nativeRef}
239 controlledDocumentJson={controlledDocumentJson}
240 themeJson={themeJson}
241 placeholder={props.placeholder ?? ""}
242 fontFamily={
243 typeof resolvedTextStyle.fontFamily === "string"
244 ? resolvedTextStyle.fontFamily
245 : regularFontFamily
246 }
247 fontSize={
248 typeof resolvedTextStyle.fontSize === "number"
249 ? resolvedTextStyle.fontSize
250 : MOBILE_TYPOGRAPHY.body.fontSize
251 }
252 lineHeight={
253 typeof resolvedTextStyle.lineHeight === "number"
254 ? resolvedTextStyle.lineHeight
255 : MOBILE_TYPOGRAPHY.body.lineHeight
256 }
257 contentInsetVertical={contentInsetVertical}
258 singleLineCentered={props.singleLineCentered ?? false}
259 editable={props.editable ?? true}
260 scrollEnabled={props.scrollEnabled ?? true}
261 autoFocus={props.autoFocus ?? false}
262 autoCorrect={props.autoCorrect ?? true}
263 spellCheck={props.spellCheck ?? true}
264 style={{ flex: 1, minHeight: 0 }}
265 onComposerChange={(event) => {
266 const acknowledgedEventCount = acceptNativeEvent(
267 event.nativeEvent.eventCount,
268 event.nativeEvent.value,
269 event.nativeEvent.selection,
270 );
271 if (acknowledgedEventCount === false) return;
272 onChangeText(event.nativeEvent.value);
273 onSelectionChange?.(event.nativeEvent.selection);
274 setMostRecentEventCount(acknowledgedEventCount);
275 forceNativeEventRender((sequence) => sequence + 1);
276 }}
277 onComposerSelectionChange={(event) => {
278 const acknowledgedEventCount = acceptNativeEvent(
279 event.nativeEvent.eventCount,
280 event.nativeEvent.value,
281 event.nativeEvent.selection,
282 );
283 if (acknowledgedEventCount === false) return;
284 // Android emits the selection change mid-mutation, before the change
285 // event, so the payload can carry post-edit text. It must reach the
286 // parent alongside the acknowledged revision, or the next render
287 // stamps the stale draft at that revision and can re-apply it over
288 // the newer native text.
289 if (event.nativeEvent.value !== props.value) {
290 onChangeText(event.nativeEvent.value);
291 }
292 onSelectionChange?.(event.nativeEvent.selection);
293 setMostRecentEventCount(acknowledgedEventCount);
294 forceNativeEventRender((sequence) => sequence + 1);
295 }}
296 onComposerPasteImages={(event) => onPasteImages?.(event.nativeEvent.uris)}
297 onComposerFocus={onFocus}
298 onComposerBlur={onBlur}
299 />
300 </TextInputWrapper>
301 );
302}
303
304export type {
305 ComposerEditorHandle,
306 ComposerEditorProps,
307 ComposerEditorSelection,
308} from "./T3ComposerEditor.types";