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