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

T3ComposerEditor.ios.tsx

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