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

T3ComposerEditor.ios.tsx

366 lines13.9 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 { 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(() => composerSkillLabels(skills), [skills]);
156 const tokensJson = useMemo(() => {
157 const tokens = collectComposerInlineTokens(props.value, {
158 preserveTrailingFrom: confirmedTokensRef.current,
159 });
160 confirmedTokensRef.current = tokens;
161 return JSON.stringify(
162 composerContextEditorTokens(props.value, tokens, skillLabels).map((token) => {
163 const record =
164 token.type === "context"
165 ? props.context?.records.find((record) => record.contextId === token.contextId)
166 : undefined;
167 return {
168 type: token.type,
169 source: token.source,
170 start: token.start,
171 end: token.end,
172 ...contextChipPresentation(token.type === "context" ? token.kind : token.type, record),
173 label:
174 token.type === "skill"
175 ? (skillLabels.get(token.value) ?? token.value)
176 : token.type === "context"
177 ? `${token.label}${props.context?.records.some((record) => record.contextId === token.contextId) ? "" : " · unavailable"}`
178 : basename(token.value),
179 detail: token.type === "context" ? composerChipSizeSuffix(record) : "",
180 iconUri:
181 token.type === "mention"
182 ? fileIconUri(token.value)
183 : record?.kind === "mention" && "path" in record
184 ? fileIconUri(record.path)
185 : null,
186 };
187 }),
188 );
189 }, [props.value, props.context, skillLabels]);
190 // Every render resolves against the snapshot history, so a render whose
191 // (value, selection) lags the acknowledged native state is stamped behind
192 // the native revision and rejected by the editor instead of re-applying a
193 // stale caret or stale text mid-typing.
194 const controlledEventCount = resolveComposerControlledEventCount(
195 props.value,
196 selection ?? null,
197 mostRecentEventCount,
198 nativeEventSnapshotsRef.current,
199 );
200 const acknowledgesLatestNativeEvent = isComposerNativeEcho(
201 props.value,
202 selection ?? null,
203 mostRecentEventCount,
204 nativeEventSnapshotsRef.current,
205 );
206 const isNativeEcho =
207 controlledEventCount === mostRecentEventCount && acknowledgesLatestNativeEvent;
208 const controlledDocumentJson = JSON.stringify({
209 value: props.value,
210 selection: isNativeEcho ? null : (selection ?? null),
211 tokensJson,
212 mostRecentEventCount: controlledEventCount,
213 isNativeEcho,
214 });
215 useEffect(() => {
216 if (!acknowledgesLatestNativeEvent) return;
217 nativeEventSnapshotsRef.current = pruneAcknowledgedComposerNativeEvents(
218 nativeEventSnapshotsRef.current,
219 mostRecentEventCount,
220 );
221 }, [acknowledgesLatestNativeEvent, mostRecentEventCount]);
222 const assumedValue = props.value;
223 useEffect(() => {
224 // A native event that arrived after this render was committed moves the
225 // acknowledged revision forward; the editor rejects this payload, so the
226 // snapshot history must not assume it applied.
227 if (isNativeEcho || controlledEventCount !== mostRecentEventCountRef.current) return;
228 nativeEventSnapshotsRef.current = assumeComposerControlledState(
229 nativeEventSnapshotsRef.current,
230 controlledEventCount,
231 assumedValue,
232 );
233 }, [assumedValue, controlledEventCount, isNativeEcho, controlledDocumentJson]);
234 const acceptNativeEvent = useCallback(
235 (eventCount: number, value: string, nextSelection: ComposerEditorSelection) => {
236 const acknowledgedEventCount = acknowledgeComposerNativeEvent(
237 mostRecentEventCountRef.current,
238 eventCount,
239 );
240 if (acknowledgedEventCount === null) {
241 return false;
242 }
243 mostRecentEventCountRef.current = acknowledgedEventCount;
244 nativeEventSnapshotsRef.current.push({
245 eventCount: acknowledgedEventCount,
246 value,
247 selection: nextSelection,
248 });
249 return acknowledgedEventCount;
250 },
251 [],
252 );
253 const themeJson = JSON.stringify(createNativeComposerTheme(theme));
254 const resolvedTextStyle = StyleSheet.flatten(textStyle) ?? {};
255 return (
256 <NativeView
257 ref={nativeRef}
258 controlledDocumentJson={controlledDocumentJson}
259 clipboardFragment={props.clipboardFragment ?? ""}
260 themeJson={themeJson}
261 placeholder={props.placeholder ?? ""}
262 fontFamily={
263 typeof resolvedTextStyle.fontFamily === "string" ? resolvedTextStyle.fontFamily : fontFamily
264 }
265 fontSize={
266 typeof resolvedTextStyle.fontSize === "number"
267 ? resolvedTextStyle.fontSize
268 : bodyText.fontSize
269 }
270 lineHeight={
271 typeof resolvedTextStyle.lineHeight === "number"
272 ? resolvedTextStyle.lineHeight
273 : bodyText.lineHeight
274 }
275 contentInsetVertical={contentInsetVertical}
276 editable={props.editable ?? true}
277 readOnly={props.readOnly ?? false}
278 enterBehavior={props.enterBehavior ?? DEFAULT_COMPOSER_ENTER_BEHAVIOR}
279 submitTitle={props.submitTitle ?? "Send Message"}
280 alternateSubmitTitle={props.alternateSubmitTitle ?? props.submitTitle ?? "Send Message"}
281 scrollEnabled={props.scrollEnabled ?? true}
282 autoFocus={props.autoFocus ?? false}
283 autoCorrect={props.autoCorrect ?? true}
284 spellCheck={props.spellCheck ?? true}
285 textPasteThresholdBytes={onPasteText ? PASTED_TEXT_ATTACHMENT_THRESHOLD_BYTES : 0}
286 maxInputChars={PROVIDER_SEND_TURN_MAX_INPUT_CHARS}
287 style={style as StyleProp<ViewStyle>}
288 onComposerChange={(event) => {
289 const acknowledgedEventCount = acceptNativeEvent(
290 event.nativeEvent.eventCount,
291 event.nativeEvent.value,
292 event.nativeEvent.selection,
293 );
294 if (acknowledgedEventCount === false) return;
295 onChangeText(event.nativeEvent.value);
296 onSelectionChange?.(event.nativeEvent.selection);
297 setMostRecentEventCount(acknowledgedEventCount);
298 forceNativeEventRender((sequence) => sequence + 1);
299 }}
300 onComposerSelectionChange={(event) => {
301 const acknowledgedEventCount = acceptNativeEvent(
302 event.nativeEvent.eventCount,
303 event.nativeEvent.value,
304 event.nativeEvent.selection,
305 );
306 if (acknowledgedEventCount === false) return;
307 // A selection change that raced a text mutation can carry post-edit
308 // text. It must reach the parent alongside the acknowledged revision,
309 // or the next render stamps the stale draft at that revision and can
310 // re-apply it over the newer native text.
311 if (event.nativeEvent.value !== props.value) {
312 onChangeText(event.nativeEvent.value);
313 }
314 onSelectionChange?.(event.nativeEvent.selection);
315 setMostRecentEventCount(acknowledgedEventCount);
316 forceNativeEventRender((sequence) => sequence + 1);
317 }}
318 onComposerPasteImages={(event) => onPasteImages?.(event.nativeEvent.uris)}
319 onComposerContextPress={(event) => props.onContextPress?.(event.nativeEvent)}
320 onComposerPasteContext={(event) => {
321 const paste = event.nativeEvent;
322 const acknowledgedEventCount = acceptNativeEvent(
323 paste.eventCount,
324 paste.value,
325 paste.selection,
326 );
327 if (acknowledgedEventCount === false) return;
328 onChangeText(paste.value);
329 onSelectionChange?.(paste.selection);
330 props.onPasteContext?.(paste);
331 setMostRecentEventCount(acknowledgedEventCount);
332 forceNativeEventRender((sequence) => sequence + 1);
333 }}
334 onComposerPasteText={(event) => {
335 const paste = event.nativeEvent;
336 const acknowledgedEventCount = acceptNativeEvent(
337 paste.eventCount,
338 paste.value,
339 paste.selection,
340 );
341 if (acknowledgedEventCount === false) return;
342 // Synchronize the draft before an async paste captures its insertion target.
343 // React props can still precede the last native keystroke.
344 onChangeText(paste.value);
345 onSelectionChange?.(paste.selection);
346 onPasteText?.(paste);
347 setMostRecentEventCount(acknowledgedEventCount);
348 forceNativeEventRender((sequence) => sequence + 1);
349 }}
350 onComposerFocus={onFocus}
351 onComposerBlur={onBlur}
352 onComposerSubmit={
353 onSubmit === undefined
354 ? undefined
355 : (event) => onSubmit(event.nativeEvent.alternate === true)
356 }
357 />
358 );
360​
361export type {
362 ComposerEditorHandle,
363 ComposerEditorProps,
364 ComposerEditorSelection,
365 ComposerTextPaste,
366} from "./T3ComposerEditor.types";