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

T3ComposerEditor.native.tsx

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