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

T3ComposerEditor.ios.tsx

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