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

T3ComposerEditor.native.tsx

389 lines14.8 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 { Platform, StyleSheet } from "react-native";
18​
19import {
20 composerChipSizeSuffix,
21 contextChipIcon,
22 contextChipAccent,
23 contextChipPresentation,
24 contextRecordFileName,
25} from "../lib/composerChipPresentation";
26import { contextChipIconUri } from "../lib/contextChipIconSource";
27import { MOBILE_TYPOGRAPHY } from "../lib/typography";
28import { useNativePaste } from "../lib/useNativePaste";
29import { FONT_FAMILIES } from "../lib/fontFamilies";
30import { useAppearancePreferences } from "../features/settings/appearance/AppearancePreferencesProvider";
31import { useUniwindTheme } from "../lib/useUniwindTheme";
32import { createNativeComposerTheme } from "../lib/nativeComposerTheme";
33import {
34 acknowledgeComposerNativeEvent,
35 assumeComposerControlledState,
36 isComposerNativeEcho,
37 pruneAcknowledgedComposerNativeEvents,
38 resolveComposerControlledEventCount,
39 type ComposerNativeEventSnapshot,
40} from "./composerEditorRevision";
41import type { ComposerEditorProps, ComposerEditorSelection } from "./T3ComposerEditor.types";
42​
43const NATIVE_MODULE_NAME = "T3ComposerEditor";
44const EMPTY_SKILLS: NonNullable<ComposerEditorProps["skills"]> = [];
45​
46type NativeEditorEvent = NativeSyntheticEvent<{
47 readonly value: string;
48 readonly selection: ComposerEditorSelection;
49 readonly eventCount: number;
50}>;
51​
52type NativeSelectionEvent = NativeSyntheticEvent<{
53 readonly value: string;
54 readonly selection: ComposerEditorSelection;
55 readonly eventCount: number;
56}>;
57​
58type NativePasteImagesEvent = NativeSyntheticEvent<{
59 readonly uris: ReadonlyArray<string>;
60}>;
61​
62type NativePasteTextEvent = NativeSyntheticEvent<{
63 readonly value: string;
64 readonly eventCount: number;
65 readonly text: string;
66 readonly selection: ComposerEditorSelection;
67}>;
68​
69interface NativeComposerEditorRef {
70 focus: () => Promise<void>;
71 blur: () => Promise<void>;
72 setSelection: (start: number, end: number) => Promise<void>;
74​
75interface NativeComposerEditorProps extends ViewProps {
76 readonly ref?: Ref<NativeComposerEditorRef>;
77 readonly controlledDocumentJson: string;
78 readonly clipboardFragment: string;
79 readonly themeJson: string;
80 readonly placeholder: string;
81 readonly fontFamily: string;
82 readonly fontSize: number;
83 readonly lineHeight: number;
84 readonly contentInsetVertical: number;
85 readonly singleLineCentered: boolean;
86 readonly editable: boolean;
87 readonly readOnly: boolean;
88 readonly scrollEnabled: boolean;
89 readonly autoFocus: boolean;
90 readonly autoCorrect: boolean;
91 readonly spellCheck: boolean;
92 readonly onComposerChange: (event: NativeEditorEvent) => void;
93 readonly onComposerSelectionChange?: (event: NativeSelectionEvent) => void;
94 readonly onComposerPasteImages?: (event: NativePasteImagesEvent) => void;
95 readonly onComposerContextPress?: (
96 event: NativeSyntheticEvent<{ source: string; start: number; end: number }>,
97 ) => void;
98 readonly onComposerPasteContext?: (
99 event: NativePasteTextEvent & NativeSyntheticEvent<{ fragment: string; html: string }>,
100 ) => void;
101 readonly textPasteThresholdBytes: number;
102 readonly maxInputChars: number;
103 readonly onComposerPasteText?: (event: NativePasteTextEvent) => void;
104 readonly onComposerFocus?: () => void;
105 readonly onComposerBlur?: () => void;
106 readonly onComposerContentSizeChange?: (
107 event: NativeSyntheticEvent<{ readonly width: number; readonly height: number }>,
108 ) => void;
110​
111const NativeView = requireNativeView<NativeComposerEditorProps>(NATIVE_MODULE_NAME);
112​
113function basename(path: string): string {
114 const separator = Math.max(path.lastIndexOf("/"), path.lastIndexOf("\\"));
115 return separator >= 0 ? path.slice(separator + 1) : path;
117​
118export function ComposerEditor({
119 ref,
120 skills = EMPTY_SKILLS,
121 selection,
122 style,
123 textStyle,
124 onChangeText,
125 onSelectionChange,
126 onPasteImages,
127 onPasteText,
128 onFocus,
129 onBlur,
130 onContentSizeChange,
131 contentInsetVertical = 0,
132 ...props
133}: ComposerEditorProps) {
134 const nativeRef = useRef<NativeComposerEditorRef>(null);
135 const mostRecentEventCountRef = useRef(0);
136 const [mostRecentEventCount, setMostRecentEventCount] = useState(0);
137 const [, forceNativeEventRender] = useState(0);
138 // Start history empty so restored drafts or recycled views receive a non-echo controlled payload.
139 const nativeEventSnapshotsRef = useRef<ComposerNativeEventSnapshot[]>([]);
140 // Tokens advance from the previous committed value; render-phase state keeps
141 // an abandoned render from leaking a trailing token into the next one.
142 const [confirmedTokens, setConfirmedTokens] = useState(() => ({
143 value: props.value,
144 tokens: collectComposerInlineTokens(props.value),
145 }));
146 let tokens = confirmedTokens.tokens;
147 if (confirmedTokens.value !== props.value) {
148 tokens = collectComposerInlineTokens(props.value, {
149 preserveTrailingFrom: confirmedTokens.tokens,
150 });
151 setConfirmedTokens({ value: props.value, tokens });
152 }
153 const theme = useUniwindTheme();
154 const handlePaste = useNativePaste((uris) => onPasteImages?.(uris));
155​
156 useImperativeHandle(
157 ref,
158 () => ({
159 focus: () => void nativeRef.current?.focus(),
160 blur: () => void nativeRef.current?.blur(),
161 setSelection: (nextSelection) =>
162 void nativeRef.current?.setSelection(nextSelection.start, nextSelection.end),
163 }),
164 [],
165 );
166​
167 const skillLabels = useMemo(() => composerSkillLabels(skills), [skills]);
168 const chipTextColor = createNativeComposerTheme(theme).text;
169 const tokensJson = useMemo(() => {
170 return JSON.stringify(
171 composerContextEditorTokens(props.value, tokens, skillLabels).map((token) => {
172 const record =
173 token.type === "context"
174 ? props.context?.records.find((record) => record.contextId === token.contextId)
175 : undefined;
176 const presentation = contextChipPresentation(
177 token.type === "context" ? token.kind : token.type,
178 record,
179 );
180 const icon = contextChipIcon(
181 presentation,
182 token.type === "mention" ? token.value : contextRecordFileName(record),
183 );
184 return {
185 type: token.type,
186 source: token.source,
187 start: token.start,
188 end: token.end,
189 accent: contextChipAccent(presentation.accent, theme, chipTextColor),
190 label:
191 token.type === "skill"
192 ? (skillLabels.get(token.value) ?? token.value)
193 : token.type === "context"
194 ? `${token.label}${props.context?.records.some((record) => record.contextId === token.contextId) ? "" : " · unavailable"}`
195 : basename(token.value),
196 detail: token.type === "context" ? composerChipSizeSuffix(record) : "",
197 iconUri: contextChipIconUri(icon),
198 tintsIcon: icon.kind === "chip",
199 };
200 }),
201 );
202 }, [props.value, tokens, props.context, skillLabels, theme, chipTextColor]);
203 // Every render resolves against the snapshot history, so a render whose
204 // (value, selection) lags the acknowledged native state is stamped behind
205 // the native revision and rejected by the editor instead of re-applying a
206 // stale caret or stale text mid-typing.
207 /* oxlint-disable react/refs -- Native controlled edits must reconcile against the last acknowledged native event before sending the next payload. */
208 const controlledEventCount = resolveComposerControlledEventCount(
209 props.value,
210 selection ?? null,
211 mostRecentEventCount,
212 nativeEventSnapshotsRef.current,
213 );
214 const acknowledgesLatestNativeEvent = isComposerNativeEcho(
215 props.value,
216 selection ?? null,
217 mostRecentEventCount,
218 nativeEventSnapshotsRef.current,
219 );
220 /* oxlint-enable react/refs */
221 const isNativeEcho =
222 controlledEventCount === mostRecentEventCount && acknowledgesLatestNativeEvent;
223 const controlledDocumentJson = JSON.stringify({
224 value: props.value,
225 selection: isNativeEcho ? null : (selection ?? null),
226 tokensJson,
227 mostRecentEventCount: controlledEventCount,
228 isNativeEcho,
229 });
230 useEffect(() => {
231 if (!acknowledgesLatestNativeEvent) return;
232 nativeEventSnapshotsRef.current = pruneAcknowledgedComposerNativeEvents(
233 nativeEventSnapshotsRef.current,
234 mostRecentEventCount,
235 );
236 }, [acknowledgesLatestNativeEvent, mostRecentEventCount, nativeEventSnapshotsRef]);
237 const assumedValue = props.value;
238 useEffect(() => {
239 // Newer native events make this payload stale; do not record it as applied.
240 if (isNativeEcho || controlledEventCount !== mostRecentEventCountRef.current) return;
241 nativeEventSnapshotsRef.current = assumeComposerControlledState(
242 nativeEventSnapshotsRef.current,
243 controlledEventCount,
244 assumedValue,
245 );
246 }, [
247 assumedValue,
248 controlledEventCount,
249 isNativeEcho,
250 // oxlint-disable-next-line react/exhaustive-effect-dependencies -- Every changed native payload, including selection-only changes, must update the assumed native snapshot.
251 controlledDocumentJson,
252 nativeEventSnapshotsRef,
253 ]);
254 const acceptNativeEvent = useCallback(
255 (eventCount: number, value: string, nextSelection: ComposerEditorSelection) => {
256 const acknowledgedEventCount = acknowledgeComposerNativeEvent(
257 mostRecentEventCountRef.current,
258 eventCount,
259 );
260 if (acknowledgedEventCount === null) {
261 return false;
262 }
263 mostRecentEventCountRef.current = acknowledgedEventCount;
264 nativeEventSnapshotsRef.current.push({
265 eventCount: acknowledgedEventCount,
266 value,
267 selection: nextSelection,
268 });
269 return acknowledgedEventCount;
270 },
271 [nativeEventSnapshotsRef],
272 );
273 const { systemColorsActive } = useAppearancePreferences();
274 const themeJson = JSON.stringify({
275 ...createNativeComposerTheme(theme),
276 selection: Platform.OS === "android" || systemColorsActive ? theme["--color-focus"] : null,
277 });
278 const resolvedTextStyle = StyleSheet.flatten(textStyle) ?? {};
279 const regularFontFamily = FONT_FAMILIES.regular;
280 return (
281 <TextInputWrapper onPaste={handlePaste} style={[{ minHeight: 0 }, style]}>
282 <NativeView
283 ref={nativeRef}
284 controlledDocumentJson={controlledDocumentJson}
285 clipboardFragment={props.clipboardFragment ?? ""}
286 themeJson={themeJson}
287 placeholder={props.placeholder ?? ""}
288 fontFamily={
289 typeof resolvedTextStyle.fontFamily === "string"
290 ? resolvedTextStyle.fontFamily
291 : regularFontFamily
292 }
293 fontSize={
294 typeof resolvedTextStyle.fontSize === "number"
295 ? resolvedTextStyle.fontSize
296 : MOBILE_TYPOGRAPHY.body.fontSize
297 }
298 lineHeight={
299 typeof resolvedTextStyle.lineHeight === "number"
300 ? resolvedTextStyle.lineHeight
301 : MOBILE_TYPOGRAPHY.body.lineHeight
302 }
303 contentInsetVertical={contentInsetVertical}
304 singleLineCentered={props.singleLineCentered ?? false}
305 editable={props.editable ?? true}
306 readOnly={props.readOnly ?? false}
307 scrollEnabled={props.scrollEnabled ?? true}
308 autoFocus={props.autoFocus ?? false}
309 autoCorrect={props.autoCorrect ?? true}
310 spellCheck={props.spellCheck ?? true}
311 textPasteThresholdBytes={onPasteText ? PASTED_TEXT_ATTACHMENT_THRESHOLD_BYTES : 0}
312 maxInputChars={PROVIDER_SEND_TURN_MAX_INPUT_CHARS}
313 style={{ flex: 1, minHeight: 0 }}
314 onComposerChange={(event) => {
315 const acknowledgedEventCount = acceptNativeEvent(
316 event.nativeEvent.eventCount,
317 event.nativeEvent.value,
318 event.nativeEvent.selection,
319 );
320 if (acknowledgedEventCount === false) return;
321 onChangeText(event.nativeEvent.value);
322 onSelectionChange?.(event.nativeEvent.selection);
323 setMostRecentEventCount(acknowledgedEventCount);
324 forceNativeEventRender((sequence) => sequence + 1);
325 }}
326 onComposerSelectionChange={(event) => {
327 const acknowledgedEventCount = acceptNativeEvent(
328 event.nativeEvent.eventCount,
329 event.nativeEvent.value,
330 event.nativeEvent.selection,
331 );
332 if (acknowledgedEventCount === false) return;
333 // Android selection events may precede text changes; publish text and revision together to reject stale drafts.
334 if (event.nativeEvent.value !== props.value) {
335 onChangeText(event.nativeEvent.value);
336 }
337 onSelectionChange?.(event.nativeEvent.selection);
338 setMostRecentEventCount(acknowledgedEventCount);
339 forceNativeEventRender((sequence) => sequence + 1);
340 }}
341 onComposerPasteImages={(event) => onPasteImages?.(event.nativeEvent.uris)}
342 onComposerContextPress={(event) => props.onContextPress?.(event.nativeEvent)}
343 onComposerPasteContext={(event) => {
344 const paste = event.nativeEvent;
345 const acknowledgedEventCount = acceptNativeEvent(
346 paste.eventCount,
347 paste.value,
348 paste.selection,
349 );
350 if (acknowledgedEventCount === false) return;
351 onChangeText(paste.value);
352 onSelectionChange?.(paste.selection);
353 props.onPasteContext?.(paste);
354 setMostRecentEventCount(acknowledgedEventCount);
355 forceNativeEventRender((sequence) => sequence + 1);
356 }}
357 onComposerPasteText={(event) => {
358 const paste = event.nativeEvent;
359 const acknowledgedEventCount = acceptNativeEvent(
360 paste.eventCount,
361 paste.value,
362 paste.selection,
363 );
364 if (acknowledgedEventCount === false) return;
365 // Sync before capturing async paste targets; props may lag the last native keystroke.
366 onChangeText(paste.value);
367 onSelectionChange?.(paste.selection);
368 onPasteText?.(paste);
369 setMostRecentEventCount(acknowledgedEventCount);
370 forceNativeEventRender((sequence) => sequence + 1);
371 }}
372 onComposerFocus={onFocus}
373 onComposerBlur={onBlur}
374 onComposerContentSizeChange={
375 onContentSizeChange === undefined
376 ? undefined
377 : (event) => onContentSizeChange(event.nativeEvent)
378 }
379 />
380 </TextInputWrapper>
381 );
383​
384export type {
385 ComposerEditorHandle,
386 ComposerEditorProps,
387 ComposerEditorSelection,
388 ComposerTextPaste,
389} from "./T3ComposerEditor.types";