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 isComposerNativeEcho,
23 pruneAcknowledgedComposerNativeEvents,
24 resolveComposerControlledEventCount,
25 type ComposerNativeEventSnapshot,
26} from "./composerEditorRevision";
27import type { ComposerEditorProps, ComposerEditorSelection } from "./T3ComposerEditor.types";
28
29const NATIVE_MODULE_NAME = "T3ComposerEditor";
30const EMPTY_SKILLS: NonNullable<ComposerEditorProps["skills"]> = [];
31
32type NativeEditorEvent = NativeSyntheticEvent<{
33 readonly value: string;
34 readonly selection: ComposerEditorSelection;
35 readonly eventCount: number;
36}>;
37
38type NativeSelectionEvent = NativeSyntheticEvent<{
39 readonly value: string;
40 readonly selection: ComposerEditorSelection;
41 readonly eventCount: number;
42}>;
43
44type NativePasteImagesEvent = NativeSyntheticEvent<{
45 readonly uris: ReadonlyArray<string>;
46}>;
47
48interface NativeComposerEditorRef {
49 focus: () => Promise<void>;
50 blur: () => Promise<void>;
51 setSelection: (start: number, end: number) => Promise<void>;
52}
53
54interface NativeComposerEditorProps extends ViewProps {
55 readonly ref?: Ref<NativeComposerEditorRef>;
56 readonly controlledDocumentJson: string;
57 readonly themeJson: string;
58 readonly placeholder: string;
59 readonly fontFamily: string;
60 readonly fontSize: number;
61 readonly lineHeight: number;
62 readonly contentInsetVertical: number;
63 readonly editable: boolean;
64 readonly scrollEnabled: boolean;
65 readonly autoFocus: boolean;
66 readonly autoCorrect: boolean;
67 readonly spellCheck: boolean;
68 readonly onComposerChange: (event: NativeEditorEvent) => void;
69 readonly onComposerSelectionChange?: (event: NativeSelectionEvent) => void;
70 readonly onComposerPasteImages?: (event: NativePasteImagesEvent) => void;
71 readonly onComposerFocus?: () => void;
72 readonly onComposerBlur?: () => void;
73 readonly onComposerSubmit?: () => void;
74}
75
76const NativeView = requireNativeView<NativeComposerEditorProps>(NATIVE_MODULE_NAME);
77
78function basename(path: string): string {
79 const separator = Math.max(path.lastIndexOf("/"), path.lastIndexOf("\\"));
80 return separator >= 0 ? path.slice(separator + 1) : path;
81}
82
83function fileIconUri(path: string): string {
84 return Image.resolveAssetSource(markdownFileIconSource(resolveMarkdownFileIcon(path))).uri;
85}
86
87export function ComposerEditor({
88 ref,
89 skills = EMPTY_SKILLS,
90 selection,
91 style,
92 textStyle,
93 onChangeText,
94 onSelectionChange,
95 onPasteImages,
96 onFocus,
97 onBlur,
98 onSubmit,
99 contentInsetVertical = 0,
100 ...props
101}: ComposerEditorProps) {
102 const nativeRef = useRef<NativeComposerEditorRef>(null);
103 const mostRecentEventCountRef = useRef(0);
104 const [mostRecentEventCount, setMostRecentEventCount] = useState(0);
105 const [nativeEventSequence, setNativeEventSequence] = useState(0);
106 const previousRenderedEventSequenceRef = useRef(0);
107 const nativeEventSnapshotsRef = useRef<ComposerNativeEventSnapshot[]>([
108 { eventCount: 0, value: props.value, selection: selection ?? null },
109 ]);
110 const confirmedTokensRef = useRef(collectComposerInlineTokens(props.value));
111 const bodyText = useScaledTextRole("body");
112 const textColor = useThemeColor("--color-foreground");
113 const placeholderColor = useThemeColor("--color-placeholder");
114 const chipBackground = useThemeColor("--color-subtle");
115 const chipBorder = useThemeColor("--color-border");
116 const chipText = useThemeColor("--color-foreground");
117 const skillBackground = useThemeColor("--color-inline-skill-background");
118 const skillBorder = useThemeColor("--color-inline-skill-border");
119 const skillText = useThemeColor("--color-inline-skill-foreground");
120 const fileTint = useThemeColor("--color-icon-muted");
121 const fontFamily = useFontFamily("regular");
122
123 useImperativeHandle(
124 ref,
125 () => ({
126 focus: () => void nativeRef.current?.focus(),
127 blur: () => void nativeRef.current?.blur(),
128 setSelection: (nextSelection) =>
129 void nativeRef.current?.setSelection(nextSelection.start, nextSelection.end),
130 }),
131 [],
132 );
133
134 const skillLabels = useMemo(
135 () => new Map(skills.map((skill) => [skill.name, skill.displayName?.trim() || skill.name])),
136 [skills],
137 );
138 const tokensJson = useMemo(() => {
139 const tokens = collectComposerInlineTokens(props.value, {
140 preserveTrailingFrom: confirmedTokensRef.current,
141 });
142 confirmedTokensRef.current = tokens;
143 return JSON.stringify(
144 tokens.map((token) => ({
145 type: token.type,
146 source: token.source,
147 start: token.start,
148 end: token.end,
149 label:
150 token.type === "skill"
151 ? (skillLabels.get(token.value) ?? token.value)
152 : basename(token.value),
153 iconUri: token.type === "mention" ? fileIconUri(token.value) : null,
154 })),
155 );
156 }, [props.value, skillLabels]);
157 const includesNativeEvent = nativeEventSequence !== previousRenderedEventSequenceRef.current;
158 const controlledEventCount = includesNativeEvent
159 ? resolveComposerControlledEventCount(
160 props.value,
161 selection ?? null,
162 mostRecentEventCount,
163 nativeEventSnapshotsRef.current,
164 )
165 : mostRecentEventCount;
166 const acknowledgesLatestNativeEvent = isComposerNativeEcho(
167 props.value,
168 selection ?? null,
169 mostRecentEventCount,
170 nativeEventSnapshotsRef.current,
171 );
172 const isNativeEcho =
173 includesNativeEvent &&
174 controlledEventCount === mostRecentEventCount &&
175 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 previousRenderedEventSequenceRef.current = nativeEventSequence;
185 }, [nativeEventSequence]);
186 useEffect(() => {
187 if (!acknowledgesLatestNativeEvent) return;
188 nativeEventSnapshotsRef.current = pruneAcknowledgedComposerNativeEvents(
189 nativeEventSnapshotsRef.current,
190 mostRecentEventCount,
191 );
192 }, [acknowledgesLatestNativeEvent, mostRecentEventCount]);
193 const acceptNativeEvent = useCallback(
194 (eventCount: number, value: string, nextSelection: ComposerEditorSelection) => {
195 const acknowledgedEventCount = acknowledgeComposerNativeEvent(
196 mostRecentEventCountRef.current,
197 eventCount,
198 );
199 if (acknowledgedEventCount === null) {
200 return false;
201 }
202 mostRecentEventCountRef.current = acknowledgedEventCount;
203 nativeEventSnapshotsRef.current.push({
204 eventCount: acknowledgedEventCount,
205 value,
206 selection: nextSelection,
207 });
208 return acknowledgedEventCount;
209 },
210 [],
211 );
212 const themeJson = JSON.stringify({
213 text: String(textColor),
214 placeholder: String(placeholderColor),
215 chipBackground: String(chipBackground),
216 chipBorder: String(chipBorder),
217 chipText: String(chipText),
218 skillBackground: String(skillBackground),
219 skillBorder: String(skillBorder),
220 skillText: String(skillText),
221 fileTint: String(fileTint),
222 });
223 const resolvedTextStyle = StyleSheet.flatten(textStyle) ?? {};
224 return (
225 <NativeView
226 ref={nativeRef}
227 controlledDocumentJson={controlledDocumentJson}
228 themeJson={themeJson}
229 placeholder={props.placeholder ?? ""}
230 fontFamily={
231 typeof resolvedTextStyle.fontFamily === "string" ? resolvedTextStyle.fontFamily : fontFamily
232 }
233 fontSize={
234 typeof resolvedTextStyle.fontSize === "number"
235 ? resolvedTextStyle.fontSize
236 : bodyText.fontSize
237 }
238 lineHeight={
239 typeof resolvedTextStyle.lineHeight === "number"
240 ? resolvedTextStyle.lineHeight
241 : bodyText.lineHeight
242 }
243 contentInsetVertical={contentInsetVertical}
244 editable={props.editable ?? true}
245 scrollEnabled={props.scrollEnabled ?? true}
246 autoFocus={props.autoFocus ?? false}
247 autoCorrect={props.autoCorrect ?? true}
248 spellCheck={props.spellCheck ?? true}
249 style={style as StyleProp<ViewStyle>}
250 onComposerChange={(event) => {
251 const acknowledgedEventCount = acceptNativeEvent(
252 event.nativeEvent.eventCount,
253 event.nativeEvent.value,
254 event.nativeEvent.selection,
255 );
256 if (acknowledgedEventCount === false) return;
257 onChangeText(event.nativeEvent.value);
258 onSelectionChange?.(event.nativeEvent.selection);
259 setMostRecentEventCount(acknowledgedEventCount);
260 setNativeEventSequence((sequence) => sequence + 1);
261 }}
262 onComposerSelectionChange={(event) => {
263 const acknowledgedEventCount = acceptNativeEvent(
264 event.nativeEvent.eventCount,
265 event.nativeEvent.value,
266 event.nativeEvent.selection,
267 );
268 if (acknowledgedEventCount === false) return;
269 onSelectionChange?.(event.nativeEvent.selection);
270 setMostRecentEventCount(acknowledgedEventCount);
271 setNativeEventSequence((sequence) => sequence + 1);
272 }}
273 onComposerPasteImages={(event) => onPasteImages?.(event.nativeEvent.uris)}
274 onComposerFocus={onFocus}
275 onComposerBlur={onBlur}
276 onComposerSubmit={onSubmit}
277 />
278 );
279}
280
281export type {
282 ComposerEditorHandle,
283 ComposerEditorProps,
284 ComposerEditorSelection,
285} from "./T3ComposerEditor.types";