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

T3ComposerEditor.ios.tsx

369 lines14.0 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 } 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 { markdownFileIconSource, markdownIconAssetUri } from "../lib/markdownFileIcons";
19import { composerChipSizeSuffix, contextChipPresentation } from "../lib/composerChipPresentation";
20import { resolveMarkdownFileIcon } from "../lib/markdownLinks";
21import { useUniwindTheme } from "../lib/useUniwindTheme";
22import { createNativeComposerTheme } from "../lib/nativeComposerTheme";
23import { FONT_FAMILIES } from "../lib/fontFamilies";
24import { useScaledTextRole } from "../features/settings/appearance/useScaledTextRole";
25import {
26 acknowledgeComposerNativeEvent,
27 assumeComposerControlledState,
28 isComposerNativeEcho,
29 pruneAcknowledgedComposerNativeEvents,
30 resolveComposerControlledEventCount,
31 type ComposerNativeEventSnapshot,
32} from "./composerEditorRevision";
33import { DEFAULT_COMPOSER_ENTER_BEHAVIOR } from "../lib/composerEnterBehavior";
34import type { ComposerEditorProps, ComposerEditorSelection } from "./T3ComposerEditor.types";
35​
36const NATIVE_MODULE_NAME = "T3ComposerEditor";
37const EMPTY_SKILLS: NonNullable<ComposerEditorProps["skills"]> = [];
38​
39type NativeEditorEvent = NativeSyntheticEvent<{
40 readonly value: string;
41 readonly selection: ComposerEditorSelection;
42 readonly eventCount: number;
43}>;
44​
45type NativeSelectionEvent = NativeSyntheticEvent<{
46 readonly value: string;
47 readonly selection: ComposerEditorSelection;
48 readonly eventCount: number;
49}>;
50​
51type NativePasteImagesEvent = NativeSyntheticEvent<{
52 readonly uris: ReadonlyArray<string>;
53}>;
54​
55type NativePasteTextEvent = NativeSyntheticEvent<{
56 readonly value: string;
57 readonly eventCount: number;
58 readonly text: string;
59 readonly selection: ComposerEditorSelection;
60}>;
61​
62interface NativeComposerEditorRef {
63 focus: () => Promise<void>;
64 blur: () => Promise<void>;
65 setSelection: (start: number, end: number) => Promise<void>;
67​
68interface NativeComposerEditorProps extends ViewProps {
69 readonly ref?: Ref<NativeComposerEditorRef>;
70 readonly controlledDocumentJson: string;
71 readonly clipboardFragment: string;
72 readonly themeJson: string;
73 readonly placeholder: string;
74 readonly fontFamily: string;
75 readonly fontSize: number;
76 readonly lineHeight: number;
77 readonly contentInsetVertical: number;
78 readonly editable: boolean;
79 readonly readOnly: boolean;
80 readonly enterBehavior: string;
81 readonly submitTitle: string;
82 readonly alternateSubmitTitle: string;
83 readonly scrollEnabled: boolean;
84 readonly autoFocus: boolean;
85 readonly autoCorrect: boolean;
86 readonly spellCheck: boolean;
87 readonly onComposerChange: (event: NativeEditorEvent) => void;
88 readonly onComposerSelectionChange?: (event: NativeSelectionEvent) => void;
89 readonly onComposerPasteImages?: (event: NativePasteImagesEvent) => void;
90 readonly onComposerContextPress?: (
91 event: NativeSyntheticEvent<{ source: string; start: number; end: number }>,
92 ) => void;
93 readonly onComposerPasteContext?: (
94 event: NativePasteTextEvent & NativeSyntheticEvent<{ fragment: string; html: string }>,
95 ) => void;
96 readonly textPasteThresholdBytes: number;
97 readonly maxInputChars: number;
98 readonly onComposerPasteText?: (event: NativePasteTextEvent) => void;
99 readonly onComposerFocus?: () => void;
100 readonly onComposerBlur?: () => void;
101 readonly onComposerSubmit?: (event: NativeSyntheticEvent<{ alternate: boolean }>) => void;
103​
104const NativeView = requireNativeView<NativeComposerEditorProps>(NATIVE_MODULE_NAME);
105​
106function basename(path: string): string {
107 const separator = Math.max(path.lastIndexOf("/"), path.lastIndexOf("\\"));
108 return separator >= 0 ? path.slice(separator + 1) : path;
110​
111function fileIconUri(path: string): string | null {
112 return markdownIconAssetUri(markdownFileIconSource(resolveMarkdownFileIcon(path))) ?? null;
114​
115export function ComposerEditor({
116 ref,
117 skills = EMPTY_SKILLS,
118 selection,
119 style,
120 textStyle,
121 onChangeText,
122 onSelectionChange,
123 onPasteImages,
124 onPasteText,
125 onFocus,
126 onBlur,
127 onSubmit,
128 contentInsetVertical = 0,
129 ...props
130}: ComposerEditorProps) {
131 const nativeRef = useRef<NativeComposerEditorRef>(null);
132 const mostRecentEventCountRef = useRef(0);
133 const [mostRecentEventCount, setMostRecentEventCount] = useState(0);
134 const [, forceNativeEventRender] = useState(0);
135 // The native editor mounts empty, so the snapshot history starts empty: the
136 // first controlled payload must be a non-echo so a restored draft (or a
137 // recycled native view) is applied rather than skipped.
138 const nativeEventSnapshotsRef = useRef<ComposerNativeEventSnapshot[]>([]);
139 const confirmedTokensRef = useRef(collectComposerInlineTokens(props.value));
140 const bodyText = useScaledTextRole("body");
141 const theme = useUniwindTheme();
142 const fontFamily = FONT_FAMILIES.regular;
143​
144 useImperativeHandle(
145 ref,
146 () => ({
147 focus: () => void nativeRef.current?.focus(),
148 blur: () => void nativeRef.current?.blur(),
149 setSelection: (nextSelection) =>
150 void nativeRef.current?.setSelection(nextSelection.start, nextSelection.end),
151 }),
152 [],
153 );
154​
155 const skillLabels = useMemo(
156 () => new Map(skills.map((skill) => [skill.name, skill.displayName?.trim() || skill.name])),
157 [skills],
158 );
159 const tokensJson = useMemo(() => {
160 const tokens = collectComposerInlineTokens(props.value, {
161 preserveTrailingFrom: confirmedTokensRef.current,
162 });
163 confirmedTokensRef.current = tokens;
164 return JSON.stringify(
165 composerContextEditorTokens(props.value, tokens).map((token) => {
166 const record =
167 token.type === "context"
168 ? props.context?.records.find((record) => record.contextId === token.contextId)
169 : undefined;
170 return {
171 type: token.type,
172 source: token.source,
173 start: token.start,
174 end: token.end,
175 ...contextChipPresentation(token.type === "context" ? token.kind : token.type, record),
176 label:
177 token.type === "skill"
178 ? (skillLabels.get(token.value) ?? token.value)
179 : token.type === "context"
180 ? `${token.label}${props.context?.records.some((record) => record.contextId === token.contextId) ? "" : " · unavailable"}`
181 : basename(token.value),
182 detail: token.type === "context" ? composerChipSizeSuffix(record) : "",
183 iconUri:
184 token.type === "mention"
185 ? fileIconUri(token.value)
186 : record?.kind === "mention" && "path" in record
187 ? fileIconUri(record.path)
188 : null,
189 };
190 }),
191 );
192 }, [props.value, props.context, skillLabels]);
193 // Every render resolves against the snapshot history, so a render whose
194 // (value, selection) lags the acknowledged native state is stamped behind
195 // the native revision and rejected by the editor instead of re-applying a
196 // stale caret or stale text mid-typing.
197 const controlledEventCount = resolveComposerControlledEventCount(
198 props.value,
199 selection ?? null,
200 mostRecentEventCount,
201 nativeEventSnapshotsRef.current,
202 );
203 const acknowledgesLatestNativeEvent = isComposerNativeEcho(
204 props.value,
205 selection ?? null,
206 mostRecentEventCount,
207 nativeEventSnapshotsRef.current,
208 );
209 const isNativeEcho =
210 controlledEventCount === mostRecentEventCount && acknowledgesLatestNativeEvent;
211 const controlledDocumentJson = JSON.stringify({
212 value: props.value,
213 selection: isNativeEcho ? null : (selection ?? null),
214 tokensJson,
215 mostRecentEventCount: controlledEventCount,
216 isNativeEcho,
217 });
218 useEffect(() => {
219 if (!acknowledgesLatestNativeEvent) return;
220 nativeEventSnapshotsRef.current = pruneAcknowledgedComposerNativeEvents(
221 nativeEventSnapshotsRef.current,
222 mostRecentEventCount,
223 );
224 }, [acknowledgesLatestNativeEvent, mostRecentEventCount]);
225 const assumedValue = props.value;
226 useEffect(() => {
227 // A native event that arrived after this render was committed moves the
228 // acknowledged revision forward; the editor rejects this payload, so the
229 // snapshot history must not assume it applied.
230 if (isNativeEcho || controlledEventCount !== mostRecentEventCountRef.current) return;
231 nativeEventSnapshotsRef.current = assumeComposerControlledState(
232 nativeEventSnapshotsRef.current,
233 controlledEventCount,
234 assumedValue,
235 );
236 }, [assumedValue, controlledEventCount, isNativeEcho, controlledDocumentJson]);
237 const acceptNativeEvent = useCallback(
238 (eventCount: number, value: string, nextSelection: ComposerEditorSelection) => {
239 const acknowledgedEventCount = acknowledgeComposerNativeEvent(
240 mostRecentEventCountRef.current,
241 eventCount,
242 );
243 if (acknowledgedEventCount === null) {
244 return false;
245 }
246 mostRecentEventCountRef.current = acknowledgedEventCount;
247 nativeEventSnapshotsRef.current.push({
248 eventCount: acknowledgedEventCount,
249 value,
250 selection: nextSelection,
251 });
252 return acknowledgedEventCount;
253 },
254 [],
255 );
256 const themeJson = JSON.stringify(createNativeComposerTheme(theme));
257 const resolvedTextStyle = StyleSheet.flatten(textStyle) ?? {};
258 return (
259 <NativeView
260 ref={nativeRef}
261 controlledDocumentJson={controlledDocumentJson}
262 clipboardFragment={props.clipboardFragment ?? ""}
263 themeJson={themeJson}
264 placeholder={props.placeholder ?? ""}
265 fontFamily={
266 typeof resolvedTextStyle.fontFamily === "string" ? resolvedTextStyle.fontFamily : fontFamily
267 }
268 fontSize={
269 typeof resolvedTextStyle.fontSize === "number"
270 ? resolvedTextStyle.fontSize
271 : bodyText.fontSize
272 }
273 lineHeight={
274 typeof resolvedTextStyle.lineHeight === "number"
275 ? resolvedTextStyle.lineHeight
276 : bodyText.lineHeight
277 }
278 contentInsetVertical={contentInsetVertical}
279 editable={props.editable ?? true}
280 readOnly={props.readOnly ?? false}
281 enterBehavior={props.enterBehavior ?? DEFAULT_COMPOSER_ENTER_BEHAVIOR}
282 submitTitle={props.submitTitle ?? "Send Message"}
283 alternateSubmitTitle={props.alternateSubmitTitle ?? props.submitTitle ?? "Send Message"}
284 scrollEnabled={props.scrollEnabled ?? true}
285 autoFocus={props.autoFocus ?? false}
286 autoCorrect={props.autoCorrect ?? true}
287 spellCheck={props.spellCheck ?? true}
288 textPasteThresholdBytes={onPasteText ? PASTED_TEXT_ATTACHMENT_THRESHOLD_BYTES : 0}
289 maxInputChars={PROVIDER_SEND_TURN_MAX_INPUT_CHARS}
290 style={style as StyleProp<ViewStyle>}
291 onComposerChange={(event) => {
292 const acknowledgedEventCount = acceptNativeEvent(
293 event.nativeEvent.eventCount,
294 event.nativeEvent.value,
295 event.nativeEvent.selection,
296 );
297 if (acknowledgedEventCount === false) return;
298 onChangeText(event.nativeEvent.value);
299 onSelectionChange?.(event.nativeEvent.selection);
300 setMostRecentEventCount(acknowledgedEventCount);
301 forceNativeEventRender((sequence) => sequence + 1);
302 }}
303 onComposerSelectionChange={(event) => {
304 const acknowledgedEventCount = acceptNativeEvent(
305 event.nativeEvent.eventCount,
306 event.nativeEvent.value,
307 event.nativeEvent.selection,
308 );
309 if (acknowledgedEventCount === false) return;
310 // A selection change that raced a text mutation can carry post-edit
311 // text. It must reach the parent alongside the acknowledged revision,
312 // or the next render stamps the stale draft at that revision and can
313 // re-apply it over the newer native text.
314 if (event.nativeEvent.value !== props.value) {
315 onChangeText(event.nativeEvent.value);
316 }
317 onSelectionChange?.(event.nativeEvent.selection);
318 setMostRecentEventCount(acknowledgedEventCount);
319 forceNativeEventRender((sequence) => sequence + 1);
320 }}
321 onComposerPasteImages={(event) => onPasteImages?.(event.nativeEvent.uris)}
322 onComposerContextPress={(event) => props.onContextPress?.(event.nativeEvent)}
323 onComposerPasteContext={(event) => {
324 const paste = event.nativeEvent;
325 const acknowledgedEventCount = acceptNativeEvent(
326 paste.eventCount,
327 paste.value,
328 paste.selection,
329 );
330 if (acknowledgedEventCount === false) return;
331 onChangeText(paste.value);
332 onSelectionChange?.(paste.selection);
333 props.onPasteContext?.(paste);
334 setMostRecentEventCount(acknowledgedEventCount);
335 forceNativeEventRender((sequence) => sequence + 1);
336 }}
337 onComposerPasteText={(event) => {
338 const paste = event.nativeEvent;
339 const acknowledgedEventCount = acceptNativeEvent(
340 paste.eventCount,
341 paste.value,
342 paste.selection,
343 );
344 if (acknowledgedEventCount === false) return;
345 // Synchronize the draft before an async paste captures its insertion target.
346 // React props can still precede the last native keystroke.
347 onChangeText(paste.value);
348 onSelectionChange?.(paste.selection);
349 onPasteText?.(paste);
350 setMostRecentEventCount(acknowledgedEventCount);
351 forceNativeEventRender((sequence) => sequence + 1);
352 }}
353 onComposerFocus={onFocus}
354 onComposerBlur={onBlur}
355 onComposerSubmit={
356 onSubmit === undefined
357 ? undefined
358 : (event) => onSubmit(event.nativeEvent.alternate === true)
359 }
360 />
361 );
363​
364export type {
365 ComposerEditorHandle,
366 ComposerEditorProps,
367 ComposerEditorSelection,
368 ComposerTextPaste,
369} from "./T3ComposerEditor.types";