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

T3ComposerEditor.ios.tsx

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