Skip to content
Source
Sign inSign up
pingdotgg/t3code
Open History to see the last commit

T3ComposerEditor.native.tsx

367 lines14.2 KB

1import { PASTED_TEXT_ATTACHMENT_THRESHOLD_BYTES } from "@t3tools/client-runtime/text-paste";
2import { PROVIDER_SEND_TURN_MAX_INPUT_CHARS } from "@t3tools/contracts";
3import { collectComposerInlineTokens } from "@t3tools/shared/composerInlineTokens";
4import { composerContextEditorTokens, composerSkillLabels } from "../lib/composerContext";
5import { requireNativeView } from "expo";
6import { TextInputWrapper } from "expo-paste-input";
7import {
8 useCallback,
9 useEffect,
10 useImperativeHandle,
11 useMemo,
12 useRef,
13 useState,
14 type Ref,
15} from "react";
16import type { NativeSyntheticEvent, ViewProps } from "react-native";
17import { Image, Platform, StyleSheet } from "react-native";
18​
19import { markdownFileIconSource, markdownIconAssetUri } from "../lib/markdownFileIcons";
20import { composerChipSizeSuffix, contextChipPresentation } from "../lib/composerChipPresentation";
21import { resolveMarkdownFileIcon } from "../lib/markdownLinks";
22import { MOBILE_TYPOGRAPHY } from "../lib/typography";
23import { useNativePaste } from "../lib/useNativePaste";
24import { FONT_FAMILIES } from "../lib/fontFamilies";
25import { useAppearancePreferences } from "../features/settings/appearance/AppearancePreferencesProvider";
26import { useUniwindTheme } from "../lib/useUniwindTheme";
27import { createNativeComposerTheme } from "../lib/nativeComposerTheme";
28import {
29 acknowledgeComposerNativeEvent,
30 assumeComposerControlledState,
31 isComposerNativeEcho,
32 pruneAcknowledgedComposerNativeEvents,
33 resolveComposerControlledEventCount,
34 type ComposerNativeEventSnapshot,
35} from "./composerEditorRevision";
36import type { ComposerEditorProps, ComposerEditorSelection } from "./T3ComposerEditor.types";
37​
38const NATIVE_MODULE_NAME = "T3ComposerEditor";
39const EMPTY_SKILLS: NonNullable<ComposerEditorProps["skills"]> = [];
40​
41type NativeEditorEvent = NativeSyntheticEvent<{
42 readonly value: string;
43 readonly selection: ComposerEditorSelection;
44 readonly eventCount: number;
45}>;
46​
47type NativeSelectionEvent = NativeSyntheticEvent<{
48 readonly value: string;
49 readonly selection: ComposerEditorSelection;
50 readonly eventCount: number;
51}>;
52​
53type NativePasteImagesEvent = NativeSyntheticEvent<{
54 readonly uris: ReadonlyArray<string>;
55}>;
56​
57type NativePasteTextEvent = NativeSyntheticEvent<{
58 readonly value: string;
59 readonly eventCount: number;
60 readonly text: string;
61 readonly selection: ComposerEditorSelection;
62}>;
63​
64interface NativeComposerEditorRef {
65 focus: () => Promise<void>;
66 blur: () => Promise<void>;
67 setSelection: (start: number, end: number) => Promise<void>;
69​
70interface NativeComposerEditorProps extends ViewProps {
71 readonly ref?: Ref<NativeComposerEditorRef>;
72 readonly controlledDocumentJson: string;
73 readonly clipboardFragment: string;
74 readonly themeJson: string;
75 readonly placeholder: string;
76 readonly fontFamily: string;
77 readonly fontSize: number;
78 readonly lineHeight: number;
79 readonly contentInsetVertical: number;
80 readonly singleLineCentered: boolean;
81 readonly editable: boolean;
82 readonly readOnly: boolean;
83 readonly scrollEnabled: boolean;
84 readonly autoFocus: boolean;
85 readonly autoCorrect: boolean;
86 readonly spellCheck: boolean;
87 readonly onComposerChange: (event: NativeEditorEvent) => void;
88 readonly onComposerSelectionChange?: (event: NativeSelectionEvent) => void;
89 readonly onComposerPasteImages?: (event: NativePasteImagesEvent) => void;
90 readonly onComposerContextPress?: (
91 event: NativeSyntheticEvent<{ source: string; start: number; end: number }>,
92 ) => void;
93 readonly onComposerPasteContext?: (
94 event: NativePasteTextEvent & NativeSyntheticEvent<{ fragment: string; html: string }>,
95 ) => void;
96 readonly textPasteThresholdBytes: number;
97 readonly maxInputChars: number;
98 readonly onComposerPasteText?: (event: NativePasteTextEvent) => void;
99 readonly onComposerFocus?: () => void;
100 readonly onComposerBlur?: () => void;
102​
103const NativeView = requireNativeView<NativeComposerEditorProps>(NATIVE_MODULE_NAME);
104​
105function basename(path: string): string {
106 const separator = Math.max(path.lastIndexOf("/"), path.lastIndexOf("\\"));
107 return separator >= 0 ? path.slice(separator + 1) : path;
109​
110function fileIconUri(path: string): string | null {
111 return markdownIconAssetUri(markdownFileIconSource(resolveMarkdownFileIcon(path))) ?? null;
113​
114export function ComposerEditor({
115 ref,
116 skills = EMPTY_SKILLS,
117 selection,
118 style,
119 textStyle,
120 onChangeText,
121 onSelectionChange,
122 onPasteImages,
123 onPasteText,
124 onFocus,
125 onBlur,
126 contentInsetVertical = 0,
127 ...props
128}: ComposerEditorProps) {
129 const nativeRef = useRef<NativeComposerEditorRef>(null);
130 const mostRecentEventCountRef = useRef(0);
131 const [mostRecentEventCount, setMostRecentEventCount] = useState(0);
132 const [, forceNativeEventRender] = useState(0);
133 // The native editor mounts empty, so the snapshot history starts empty: the
134 // first controlled payload must be a non-echo so a restored draft (or a
135 // recycled native view) is applied rather than skipped.
136 const nativeEventSnapshotsRef = useRef<ComposerNativeEventSnapshot[]>([]);
137 const [initialConfirmedTokens] = useState(() => collectComposerInlineTokens(props.value));
138 const confirmedTokensRef = useRef(initialConfirmedTokens);
139 const theme = useUniwindTheme();
140 const handlePaste = useNativePaste((uris) => onPasteImages?.(uris));
141​
142 useImperativeHandle(
143 ref,
144 () => ({
145 focus: () => void nativeRef.current?.focus(),
146 blur: () => void nativeRef.current?.blur(),
147 setSelection: (nextSelection) =>
148 void nativeRef.current?.setSelection(nextSelection.start, nextSelection.end),
149 }),
150 [],
151 );
152​
153 const skillLabels = useMemo(() => composerSkillLabels(skills), [skills]);
154 const tokensJson = useMemo(() => {
155 const tokens = collectComposerInlineTokens(props.value, {
156 preserveTrailingFrom: confirmedTokensRef.current,
157 });
158 confirmedTokensRef.current = tokens;
159 return JSON.stringify(
160 composerContextEditorTokens(props.value, tokens, skillLabels).map((token) => {
161 const record =
162 token.type === "context"
163 ? props.context?.records.find((record) => record.contextId === token.contextId)
164 : undefined;
165 return {
166 type: token.type,
167 source: token.source,
168 start: token.start,
169 end: token.end,
170 ...contextChipPresentation(token.type === "context" ? token.kind : token.type, record),
171 label:
172 token.type === "skill"
173 ? (skillLabels.get(token.value) ?? token.value)
174 : token.type === "context"
175 ? `${token.label}${props.context?.records.some((record) => record.contextId === token.contextId) ? "" : " · unavailable"}`
176 : basename(token.value),
177 detail: token.type === "context" ? composerChipSizeSuffix(record) : "",
178 iconUri:
179 token.type === "mention"
180 ? fileIconUri(token.value)
181 : record?.kind === "mention" && "path" in record
182 ? fileIconUri(record.path)
183 : null,
184 };
185 }),
186 );
187 }, [props.value, props.context, skillLabels]);
188 // Every render resolves against the snapshot history, so a render whose
189 // (value, selection) lags the acknowledged native state is stamped behind
190 // the native revision and rejected by the editor instead of re-applying a
191 // stale caret or stale text mid-typing.
192 const controlledEventCount = resolveComposerControlledEventCount(
193 props.value,
194 selection ?? null,
195 mostRecentEventCount,
196 nativeEventSnapshotsRef.current,
197 );
198 const acknowledgesLatestNativeEvent = isComposerNativeEcho(
199 props.value,
200 selection ?? null,
201 mostRecentEventCount,
202 nativeEventSnapshotsRef.current,
203 );
204 const isNativeEcho =
205 controlledEventCount === mostRecentEventCount && acknowledgesLatestNativeEvent;
206 const controlledDocumentJson = JSON.stringify({
207 value: props.value,
208 selection: isNativeEcho ? null : (selection ?? null),
209 tokensJson,
210 mostRecentEventCount: controlledEventCount,
211 isNativeEcho,
212 });
213 useEffect(() => {
214 if (!acknowledgesLatestNativeEvent) return;
215 nativeEventSnapshotsRef.current = pruneAcknowledgedComposerNativeEvents(
216 nativeEventSnapshotsRef.current,
217 mostRecentEventCount,
218 );
219 }, [acknowledgesLatestNativeEvent, mostRecentEventCount]);
220 const assumedValue = props.value;
221 useEffect(() => {
222 // A native event that arrived after this render was committed moves the
223 // acknowledged revision forward; the editor rejects this payload, so the
224 // snapshot history must not assume it applied.
225 if (isNativeEcho || controlledEventCount !== mostRecentEventCountRef.current) return;
226 nativeEventSnapshotsRef.current = assumeComposerControlledState(
227 nativeEventSnapshotsRef.current,
228 controlledEventCount,
229 assumedValue,
230 );
231 }, [assumedValue, controlledEventCount, isNativeEcho, controlledDocumentJson]);
232 const acceptNativeEvent = useCallback(
233 (eventCount: number, value: string, nextSelection: ComposerEditorSelection) => {
234 const acknowledgedEventCount = acknowledgeComposerNativeEvent(
235 mostRecentEventCountRef.current,
236 eventCount,
237 );
238 if (acknowledgedEventCount === null) {
239 return false;
240 }
241 mostRecentEventCountRef.current = acknowledgedEventCount;
242 nativeEventSnapshotsRef.current.push({
243 eventCount: acknowledgedEventCount,
244 value,
245 selection: nextSelection,
246 });
247 return acknowledgedEventCount;
248 },
249 [],
250 );
251 const { systemColorsActive } = useAppearancePreferences();
252 const themeJson = JSON.stringify({
253 ...createNativeComposerTheme(theme),
254 selection: Platform.OS === "android" || systemColorsActive ? theme["--color-focus"] : null,
255 });
256 const resolvedTextStyle = StyleSheet.flatten(textStyle) ?? {};
257 const regularFontFamily = FONT_FAMILIES.regular;
258 return (
259 <TextInputWrapper onPaste={handlePaste} style={[{ minHeight: 0 }, style]}>
260 <NativeView
261 ref={nativeRef}
262 controlledDocumentJson={controlledDocumentJson}
263 clipboardFragment={props.clipboardFragment ?? ""}
264 themeJson={themeJson}
265 placeholder={props.placeholder ?? ""}
266 fontFamily={
267 typeof resolvedTextStyle.fontFamily === "string"
268 ? resolvedTextStyle.fontFamily
269 : regularFontFamily
270 }
271 fontSize={
272 typeof resolvedTextStyle.fontSize === "number"
273 ? resolvedTextStyle.fontSize
274 : MOBILE_TYPOGRAPHY.body.fontSize
275 }
276 lineHeight={
277 typeof resolvedTextStyle.lineHeight === "number"
278 ? resolvedTextStyle.lineHeight
279 : MOBILE_TYPOGRAPHY.body.lineHeight
280 }
281 contentInsetVertical={contentInsetVertical}
282 singleLineCentered={props.singleLineCentered ?? false}
283 editable={props.editable ?? true}
284 readOnly={props.readOnly ?? false}
285 scrollEnabled={props.scrollEnabled ?? true}
286 autoFocus={props.autoFocus ?? false}
287 autoCorrect={props.autoCorrect ?? true}
288 spellCheck={props.spellCheck ?? true}
289 textPasteThresholdBytes={onPasteText ? PASTED_TEXT_ATTACHMENT_THRESHOLD_BYTES : 0}
290 maxInputChars={PROVIDER_SEND_TURN_MAX_INPUT_CHARS}
291 style={{ flex: 1, minHeight: 0 }}
292 onComposerChange={(event) => {
293 const acknowledgedEventCount = acceptNativeEvent(
294 event.nativeEvent.eventCount,
295 event.nativeEvent.value,
296 event.nativeEvent.selection,
297 );
298 if (acknowledgedEventCount === false) return;
299 onChangeText(event.nativeEvent.value);
300 onSelectionChange?.(event.nativeEvent.selection);
301 setMostRecentEventCount(acknowledgedEventCount);
302 forceNativeEventRender((sequence) => sequence + 1);
303 }}
304 onComposerSelectionChange={(event) => {
305 const acknowledgedEventCount = acceptNativeEvent(
306 event.nativeEvent.eventCount,
307 event.nativeEvent.value,
308 event.nativeEvent.selection,
309 );
310 if (acknowledgedEventCount === false) return;
311 // Android emits the selection change mid-mutation, before the change
312 // event, so the payload can carry post-edit text. It must reach the
313 // parent alongside the acknowledged revision, or the next render
314 // stamps the stale draft at that revision and can re-apply it over
315 // the newer native text.
316 if (event.nativeEvent.value !== props.value) {
317 onChangeText(event.nativeEvent.value);
318 }
319 onSelectionChange?.(event.nativeEvent.selection);
320 setMostRecentEventCount(acknowledgedEventCount);
321 forceNativeEventRender((sequence) => sequence + 1);
322 }}
323 onComposerPasteImages={(event) => onPasteImages?.(event.nativeEvent.uris)}
324 onComposerContextPress={(event) => props.onContextPress?.(event.nativeEvent)}
325 onComposerPasteContext={(event) => {
326 const paste = event.nativeEvent;
327 const acknowledgedEventCount = acceptNativeEvent(
328 paste.eventCount,
329 paste.value,
330 paste.selection,
331 );
332 if (acknowledgedEventCount === false) return;
333 onChangeText(paste.value);
334 onSelectionChange?.(paste.selection);
335 props.onPasteContext?.(paste);
336 setMostRecentEventCount(acknowledgedEventCount);
337 forceNativeEventRender((sequence) => sequence + 1);
338 }}
339 onComposerPasteText={(event) => {
340 const paste = event.nativeEvent;
341 const acknowledgedEventCount = acceptNativeEvent(
342 paste.eventCount,
343 paste.value,
344 paste.selection,
345 );
346 if (acknowledgedEventCount === false) return;
347 // Synchronize the draft before an async paste captures its insertion target.
348 // React props can still precede the last native keystroke.
349 onChangeText(paste.value);
350 onSelectionChange?.(paste.selection);
351 onPasteText?.(paste);
352 setMostRecentEventCount(acknowledgedEventCount);
353 forceNativeEventRender((sequence) => sequence + 1);
354 }}
355 onComposerFocus={onFocus}
356 onComposerBlur={onBlur}
357 />
358 </TextInputWrapper>
359 );
361​
362export type {
363 ComposerEditorHandle,
364 ComposerEditorProps,
365 ComposerEditorSelection,
366 ComposerTextPaste,
367} from "./T3ComposerEditor.types";