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 isComposerNativeEcho,
25 pruneAcknowledgedComposerNativeEvents,
26 resolveComposerControlledEventCount,
27 type ComposerNativeEventSnapshot,
28} from "./composerEditorRevision";
29import type { ComposerEditorProps, ComposerEditorSelection } from "./T3ComposerEditor.types";
30
31const NATIVE_MODULE_NAME = "T3ComposerEditor";
32const EMPTY_SKILLS: NonNullable<ComposerEditorProps["skills"]> = [];
33
34type NativeEditorEvent = NativeSyntheticEvent<{
35 readonly value: string;
36 readonly selection: ComposerEditorSelection;
37 readonly eventCount: number;
38}>;
39
40type NativeSelectionEvent = NativeSyntheticEvent<{
41 readonly value: string;
42 readonly selection: ComposerEditorSelection;
43 readonly eventCount: number;
44}>;
45
46type NativePasteImagesEvent = NativeSyntheticEvent<{
47 readonly uris: ReadonlyArray<string>;
48}>;
49
50interface NativeComposerEditorRef {
51 focus: () => Promise<void>;
52 blur: () => Promise<void>;
53 setSelection: (start: number, end: number) => Promise<void>;
54}
55
56interface NativeComposerEditorProps extends ViewProps {
57 readonly ref?: Ref<NativeComposerEditorRef>;
58 readonly controlledDocumentJson: string;
59 readonly themeJson: string;
60 readonly placeholder: string;
61 readonly fontFamily: string;
62 readonly fontSize: number;
63 readonly lineHeight: number;
64 readonly contentInsetVertical: number;
65 readonly singleLineCentered: boolean;
66 readonly editable: boolean;
67 readonly scrollEnabled: boolean;
68 readonly autoFocus: boolean;
69 readonly autoCorrect: boolean;
70 readonly spellCheck: boolean;
71 readonly onComposerChange: (event: NativeEditorEvent) => void;
72 readonly onComposerSelectionChange?: (event: NativeSelectionEvent) => void;
73 readonly onComposerPasteImages?: (event: NativePasteImagesEvent) => void;
74 readonly onComposerFocus?: () => void;
75 readonly onComposerBlur?: () => void;
76}
77
78const NativeView = requireNativeView<NativeComposerEditorProps>(NATIVE_MODULE_NAME);
79
80function basename(path: string): string {
81 const separator = Math.max(path.lastIndexOf("/"), path.lastIndexOf("\\"));
82 return separator >= 0 ? path.slice(separator + 1) : path;
83}
84
85function fileIconUri(path: string): string {
86 return Image.resolveAssetSource(markdownFileIconSource(resolveMarkdownFileIcon(path))).uri;
87}
88
89export function ComposerEditor({
90 ref,
91 skills = EMPTY_SKILLS,
92 selection,
93 style,
94 textStyle,
95 onChangeText,
96 onSelectionChange,
97 onPasteImages,
98 onFocus,
99 onBlur,
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 [nativeEventSequence, setNativeEventSequence] = useState(0);
107 const previousRenderedEventSequenceRef = useRef(0);
108 const nativeEventSnapshotsRef = useRef<ComposerNativeEventSnapshot[]>([
109 { eventCount: 0, value: props.value, selection: selection ?? null },
110 ]);
111 const [initialConfirmedTokens] = useState(() => collectComposerInlineTokens(props.value));
112 const confirmedTokensRef = useRef(initialConfirmedTokens);
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 handlePaste = useNativePaste((uris) => onPasteImages?.(uris));
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 const includesNativeEvent = nativeEventSequence !== previousRenderedEventSequenceRef.current;
159 const controlledEventCount = includesNativeEvent
160 ? resolveComposerControlledEventCount(
161 props.value,
162 selection ?? null,
163 mostRecentEventCount,
164 nativeEventSnapshotsRef.current,
165 )
166 : mostRecentEventCount;
167 const acknowledgesLatestNativeEvent = isComposerNativeEcho(
168 props.value,
169 selection ?? null,
170 mostRecentEventCount,
171 nativeEventSnapshotsRef.current,
172 );
173 const isNativeEcho =
174 includesNativeEvent &&
175 controlledEventCount === mostRecentEventCount &&
176 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 previousRenderedEventSequenceRef.current = nativeEventSequence;
186 }, [nativeEventSequence]);
187 useEffect(() => {
188 if (!acknowledgesLatestNativeEvent) return;
189 nativeEventSnapshotsRef.current = pruneAcknowledgedComposerNativeEvents(
190 nativeEventSnapshotsRef.current,
191 mostRecentEventCount,
192 );
193 }, [acknowledgesLatestNativeEvent, mostRecentEventCount]);
194 const acceptNativeEvent = useCallback(
195 (eventCount: number, value: string, nextSelection: ComposerEditorSelection) => {
196 const acknowledgedEventCount = acknowledgeComposerNativeEvent(
197 mostRecentEventCountRef.current,
198 eventCount,
199 );
200 if (acknowledgedEventCount === null) {
201 return false;
202 }
203 mostRecentEventCountRef.current = acknowledgedEventCount;
204 nativeEventSnapshotsRef.current.push({
205 eventCount: acknowledgedEventCount,
206 value,
207 selection: nextSelection,
208 });
209 return acknowledgedEventCount;
210 },
211 [],
212 );
213 const themeJson = JSON.stringify({
214 text: String(textColor),
215 placeholder: String(placeholderColor),
216 chipBackground: String(chipBackground),
217 chipBorder: String(chipBorder),
218 chipText: String(chipText),
219 skillBackground: String(skillBackground),
220 skillBorder: String(skillBorder),
221 skillText: String(skillText),
222 fileTint: String(fileTint),
223 });
224 const resolvedTextStyle = StyleSheet.flatten(textStyle) ?? {};
225 const regularFontFamily = useFontFamily("regular");
226 return (
227 <TextInputWrapper onPaste={handlePaste} style={[{ minHeight: 0 }, style]}>
228 <NativeView
229 ref={nativeRef}
230 controlledDocumentJson={controlledDocumentJson}
231 themeJson={themeJson}
232 placeholder={props.placeholder ?? ""}
233 fontFamily={
234 typeof resolvedTextStyle.fontFamily === "string"
235 ? resolvedTextStyle.fontFamily
236 : regularFontFamily
237 }
238 fontSize={
239 typeof resolvedTextStyle.fontSize === "number"
240 ? resolvedTextStyle.fontSize
241 : MOBILE_TYPOGRAPHY.body.fontSize
242 }
243 lineHeight={
244 typeof resolvedTextStyle.lineHeight === "number"
245 ? resolvedTextStyle.lineHeight
246 : MOBILE_TYPOGRAPHY.body.lineHeight
247 }
248 contentInsetVertical={contentInsetVertical}
249 singleLineCentered={props.singleLineCentered ?? false}
250 editable={props.editable ?? true}
251 scrollEnabled={props.scrollEnabled ?? true}
252 autoFocus={props.autoFocus ?? false}
253 autoCorrect={props.autoCorrect ?? true}
254 spellCheck={props.spellCheck ?? true}
255 style={{ flex: 1, minHeight: 0 }}
256 onComposerChange={(event) => {
257 const acknowledgedEventCount = acceptNativeEvent(
258 event.nativeEvent.eventCount,
259 event.nativeEvent.value,
260 event.nativeEvent.selection,
261 );
262 if (acknowledgedEventCount === false) return;
263 onChangeText(event.nativeEvent.value);
264 onSelectionChange?.(event.nativeEvent.selection);
265 setMostRecentEventCount(acknowledgedEventCount);
266 setNativeEventSequence((sequence) => sequence + 1);
267 }}
268 onComposerSelectionChange={(event) => {
269 const acknowledgedEventCount = acceptNativeEvent(
270 event.nativeEvent.eventCount,
271 event.nativeEvent.value,
272 event.nativeEvent.selection,
273 );
274 if (acknowledgedEventCount === false) return;
275 onSelectionChange?.(event.nativeEvent.selection);
276 setMostRecentEventCount(acknowledgedEventCount);
277 setNativeEventSequence((sequence) => sequence + 1);
278 }}
279 onComposerPasteImages={(event) => onPasteImages?.(event.nativeEvent.uris)}
280 onComposerFocus={onFocus}
281 onComposerBlur={onBlur}
282 />
283 </TextInputWrapper>
284 );
285}
286
287export type {
288 ComposerEditorHandle,
289 ComposerEditorProps,
290 ComposerEditorSelection,
291} from "./T3ComposerEditor.types";