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

T3ComposerEditor.ios.tsx

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