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

T3ComposerEditor.native.tsx

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