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