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

T3ComposerEditor.native.tsx

399 lines15.5 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​
113// A view command rejects with "Unable to find the view" when the composer's native view is
114// unmounted, which can happen while an open question hides the composer slot. There is nothing
115// to act on then.
116function settleViewCommand(command: Promise<void> | undefined): void {
117 command?.catch(() => undefined);
119​
120function basename(path: string): string {
121 const separator = Math.max(path.lastIndexOf("/"), path.lastIndexOf("\\"));
122 return separator >= 0 ? path.slice(separator + 1) : path;
124​
125export function ComposerEditor({
126 ref,
127 skills = EMPTY_SKILLS,
128 selection,
129 style,
130 textStyle,
131 onChangeText,
132 onSelectionChange,
133 onPasteImages,
134 onPasteText,
135 onFocus,
136 onBlur,
137 onContentSizeChange,
138 contentInsetVertical = 0,
139 ...props
140}: ComposerEditorProps) {
141 const nativeRef = useRef<NativeComposerEditorRef>(null);
142 const mostRecentEventCountRef = useRef(0);
143 const [mostRecentEventCount, setMostRecentEventCount] = useState(0);
144 const [, forceNativeEventRender] = useState(0);
145 // Start history empty so restored drafts or recycled views receive a non-echo controlled payload.
146 const nativeEventSnapshotsRef = useRef<ComposerNativeEventSnapshot[]>([]);
147 // Tokens advance from the previous committed value; render-phase state keeps
148 // an abandoned render from leaking a trailing token into the next one.
149 const [confirmedTokens, setConfirmedTokens] = useState(() => ({
150 value: props.value,
151 tokens: collectComposerInlineTokens(props.value),
152 }));
153 let tokens = confirmedTokens.tokens;
154 if (confirmedTokens.value !== props.value) {
155 tokens = collectComposerInlineTokens(props.value, {
156 preserveTrailingFrom: confirmedTokens.tokens,
157 });
158 setConfirmedTokens({ value: props.value, tokens });
159 }
160 const theme = useUniwindTheme();
161 const handlePaste = useNativePaste((uris) => onPasteImages?.(uris));
162​
163 useImperativeHandle(
164 ref,
165 () => ({
166 focus: () => settleViewCommand(nativeRef.current?.focus()),
167 blur: () => settleViewCommand(nativeRef.current?.blur()),
168 setSelection: (nextSelection) =>
169 settleViewCommand(nativeRef.current?.setSelection(nextSelection.start, nextSelection.end)),
170 flushPendingInput: async () => {},
171 }),
172 [],
173 );
174​
175 const skillLabels = useMemo(() => composerSkillLabels(skills), [skills]);
176 const chipTextColor = createNativeComposerTheme(theme).text;
177 const tokensJson = useMemo(() => {
178 return JSON.stringify(
179 composerContextEditorTokens(props.value, tokens, skillLabels).map((token) => {
180 const record =
181 token.type === "context"
182 ? props.context?.records.find((record) => record.contextId === token.contextId)
183 : undefined;
184 const presentation = contextChipPresentation(
185 token.type === "context" ? token.kind : token.type,
186 record,
187 );
188 const icon = contextChipIcon(
189 presentation,
190 token.type === "mention" ? token.value : contextRecordFileName(record),
191 );
192 return {
193 type: token.type,
194 source: token.source,
195 start: token.start,
196 end: token.end,
197 accent: contextChipAccent(presentation.accent, theme, chipTextColor),
198 label:
199 token.type === "skill"
200 ? (skillLabels.get(token.value) ?? token.value)
201 : token.type === "context"
202 ? `${token.label}${props.context?.records.some((record) => record.contextId === token.contextId) ? "" : " · unavailable"}`
203 : basename(token.value),
204 detail: token.type === "context" ? composerChipSizeSuffix(record) : "",
205 iconUri: contextChipIconUri(icon),
206 tintsIcon: icon.kind === "chip",
207 };
208 }),
209 );
210 }, [props.value, tokens, props.context, skillLabels, theme, chipTextColor]);
211 // Every render resolves against the snapshot history, so a render whose
212 // (value, selection) lags the acknowledged native state is stamped behind
213 // the native revision and rejected by the editor instead of re-applying a
214 // stale caret or stale text mid-typing.
215 /* oxlint-disable react/refs -- Native controlled edits must reconcile against the last acknowledged native event before sending the next payload. */
216 const controlledEventCount = resolveComposerControlledEventCount(
217 props.value,
218 selection ?? null,
219 mostRecentEventCount,
220 nativeEventSnapshotsRef.current,
221 );
222 const acknowledgesLatestNativeEvent = isComposerNativeEcho(
223 props.value,
224 selection ?? null,
225 mostRecentEventCount,
226 nativeEventSnapshotsRef.current,
227 );
228 /* oxlint-enable react/refs */
229 const isNativeEcho =
230 controlledEventCount === mostRecentEventCount && acknowledgesLatestNativeEvent;
231 const controlledDocumentJson = JSON.stringify({
232 value: props.value,
233 selection: isNativeEcho ? null : (selection ?? null),
234 tokensJson,
235 mostRecentEventCount: controlledEventCount,
236 isNativeEcho,
237 });
238 // oxlint-disable-next-line t3code/no-unreasoned-state-sync -- prunes native editor event snapshots once a committed payload acknowledges them
239 useEffect(() => {
240 if (!acknowledgesLatestNativeEvent) return;
241 nativeEventSnapshotsRef.current = pruneAcknowledgedComposerNativeEvents(
242 nativeEventSnapshotsRef.current,
243 mostRecentEventCount,
244 );
245 }, [acknowledgesLatestNativeEvent, mostRecentEventCount, nativeEventSnapshotsRef]);
246 const assumedValue = props.value;
247 // oxlint-disable-next-line t3code/no-unreasoned-state-sync -- records the committed controlled payload as the native editor's assumed state
248 useEffect(() => {
249 // Newer native events make this payload stale; do not record it as applied.
250 if (isNativeEcho || controlledEventCount !== mostRecentEventCountRef.current) return;
251 nativeEventSnapshotsRef.current = assumeComposerControlledState(
252 nativeEventSnapshotsRef.current,
253 controlledEventCount,
254 assumedValue,
255 );
256 }, [
257 assumedValue,
258 controlledEventCount,
259 isNativeEcho,
260 // oxlint-disable-next-line react/exhaustive-effect-dependencies -- Every changed native payload, including selection-only changes, must update the assumed native snapshot.
261 controlledDocumentJson,
262 nativeEventSnapshotsRef,
263 ]);
264 const acceptNativeEvent = useCallback(
265 (eventCount: number, value: string, nextSelection: ComposerEditorSelection) => {
266 const acknowledgedEventCount = acknowledgeComposerNativeEvent(
267 mostRecentEventCountRef.current,
268 eventCount,
269 );
270 if (acknowledgedEventCount === null) {
271 return false;
272 }
273 mostRecentEventCountRef.current = acknowledgedEventCount;
274 nativeEventSnapshotsRef.current.push({
275 eventCount: acknowledgedEventCount,
276 value,
277 selection: nextSelection,
278 });
279 return acknowledgedEventCount;
280 },
281 [nativeEventSnapshotsRef],
282 );
283 const { systemColorsActive } = useAppearancePreferences();
284 const themeJson = JSON.stringify({
285 ...createNativeComposerTheme(theme),
286 selection: Platform.OS === "android" || systemColorsActive ? theme["--color-focus"] : null,
287 });
288 const resolvedTextStyle = StyleSheet.flatten(textStyle) ?? {};
289 const regularFontFamily = FONT_FAMILIES.regular;
290 return (
291 <TextInputWrapper onPaste={handlePaste} style={[{ minHeight: 0 }, style]}>
292 <NativeView
293 ref={nativeRef}
294 controlledDocumentJson={controlledDocumentJson}
295 clipboardFragment={props.clipboardFragment ?? ""}
296 themeJson={themeJson}
297 placeholder={props.placeholder ?? ""}
298 fontFamily={
299 typeof resolvedTextStyle.fontFamily === "string"
300 ? resolvedTextStyle.fontFamily
301 : regularFontFamily
302 }
303 fontSize={
304 typeof resolvedTextStyle.fontSize === "number"
305 ? resolvedTextStyle.fontSize
306 : MOBILE_TYPOGRAPHY.body.fontSize
307 }
308 lineHeight={
309 typeof resolvedTextStyle.lineHeight === "number"
310 ? resolvedTextStyle.lineHeight
311 : MOBILE_TYPOGRAPHY.body.lineHeight
312 }
313 contentInsetVertical={contentInsetVertical}
314 singleLineCentered={props.singleLineCentered ?? false}
315 editable={props.editable ?? true}
316 readOnly={props.readOnly ?? false}
317 scrollEnabled={props.scrollEnabled ?? true}
318 autoFocus={props.autoFocus ?? false}
319 autoCorrect={props.autoCorrect ?? true}
320 spellCheck={props.spellCheck ?? true}
321 textPasteThresholdBytes={onPasteText ? PASTED_TEXT_ATTACHMENT_THRESHOLD_BYTES : 0}
322 maxInputChars={PROVIDER_SEND_TURN_MAX_INPUT_CHARS}
323 style={{ flex: 1, minHeight: 0 }}
324 onComposerChange={(event) => {
325 const acknowledgedEventCount = acceptNativeEvent(
326 event.nativeEvent.eventCount,
327 event.nativeEvent.value,
328 event.nativeEvent.selection,
329 );
330 if (acknowledgedEventCount === false) return;
331 onChangeText(event.nativeEvent.value);
332 onSelectionChange?.(event.nativeEvent.selection);
333 setMostRecentEventCount(acknowledgedEventCount);
334 forceNativeEventRender((sequence) => sequence + 1);
335 }}
336 onComposerSelectionChange={(event) => {
337 const acknowledgedEventCount = acceptNativeEvent(
338 event.nativeEvent.eventCount,
339 event.nativeEvent.value,
340 event.nativeEvent.selection,
341 );
342 if (acknowledgedEventCount === false) return;
343 // Android selection events may precede text changes; publish text and revision together to reject stale drafts.
344 if (event.nativeEvent.value !== props.value) {
345 onChangeText(event.nativeEvent.value);
346 }
347 onSelectionChange?.(event.nativeEvent.selection);
348 setMostRecentEventCount(acknowledgedEventCount);
349 forceNativeEventRender((sequence) => sequence + 1);
350 }}
351 onComposerPasteImages={(event) => onPasteImages?.(event.nativeEvent.uris)}
352 onComposerContextPress={(event) => props.onContextPress?.(event.nativeEvent)}
353 onComposerPasteContext={(event) => {
354 const paste = event.nativeEvent;
355 const acknowledgedEventCount = acceptNativeEvent(
356 paste.eventCount,
357 paste.value,
358 paste.selection,
359 );
360 if (acknowledgedEventCount === false) return;
361 onChangeText(paste.value);
362 onSelectionChange?.(paste.selection);
363 props.onPasteContext?.(paste);
364 setMostRecentEventCount(acknowledgedEventCount);
365 forceNativeEventRender((sequence) => sequence + 1);
366 }}
367 onComposerPasteText={(event) => {
368 const paste = event.nativeEvent;
369 const acknowledgedEventCount = acceptNativeEvent(
370 paste.eventCount,
371 paste.value,
372 paste.selection,
373 );
374 if (acknowledgedEventCount === false) return;
375 // Sync before capturing async paste targets; props may lag the last native keystroke.
376 onChangeText(paste.value);
377 onSelectionChange?.(paste.selection);
378 onPasteText?.(paste);
379 setMostRecentEventCount(acknowledgedEventCount);
380 forceNativeEventRender((sequence) => sequence + 1);
381 }}
382 onComposerFocus={onFocus}
383 onComposerBlur={onBlur}
384 onComposerContentSizeChange={
385 onContentSizeChange === undefined
386 ? undefined
387 : (event) => onContentSizeChange(event.nativeEvent)
388 }
389 />
390 </TextInputWrapper>
391 );
393​
394export type {
395 ComposerEditorHandle,
396 ComposerEditorProps,
397 ComposerEditorSelection,
398 ComposerTextPaste,
399} from "./T3ComposerEditor.types";