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

T3ComposerEditor.native.tsx

376 lines14.5 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 { 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 { createNativeComposerTheme } from "../lib/nativeComposerTheme";
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 ...createNativeComposerTheme(theme),
263 selection: Platform.OS === "android" || systemColorsActive ? theme["--color-focus"] : null,
264 });
265 const resolvedTextStyle = StyleSheet.flatten(textStyle) ?? {};
266 const regularFontFamily = useFontFamily("regular");
267 return (
268 <TextInputWrapper onPaste={handlePaste} style={[{ minHeight: 0 }, style]}>
269 <NativeView
270 ref={nativeRef}
271 controlledDocumentJson={controlledDocumentJson}
272 clipboardFragment={props.clipboardFragment ?? ""}
273 themeJson={themeJson}
274 placeholder={props.placeholder ?? ""}
275 fontFamily={
276 typeof resolvedTextStyle.fontFamily === "string"
277 ? resolvedTextStyle.fontFamily
278 : regularFontFamily
279 }
280 fontSize={
281 typeof resolvedTextStyle.fontSize === "number"
282 ? resolvedTextStyle.fontSize
283 : MOBILE_TYPOGRAPHY.body.fontSize
284 }
285 lineHeight={
286 typeof resolvedTextStyle.lineHeight === "number"
287 ? resolvedTextStyle.lineHeight
288 : MOBILE_TYPOGRAPHY.body.lineHeight
289 }
290 contentInsetVertical={contentInsetVertical}
291 singleLineCentered={props.singleLineCentered ?? false}
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={{ flex: 1, minHeight: 0 }}
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 // Android emits the selection change mid-mutation, before the change
321 // event, so the payload can carry post-edit text. It must reach the
322 // parent alongside the acknowledged revision, or the next render
323 // stamps the stale draft at that revision and can re-apply it over
324 // the newer native text.
325 if (event.nativeEvent.value !== props.value) {
326 onChangeText(event.nativeEvent.value);
327 }
328 onSelectionChange?.(event.nativeEvent.selection);
329 setMostRecentEventCount(acknowledgedEventCount);
330 forceNativeEventRender((sequence) => sequence + 1);
331 }}
332 onComposerPasteImages={(event) => onPasteImages?.(event.nativeEvent.uris)}
333 onComposerContextPress={(event) => props.onContextPress?.(event.nativeEvent)}
334 onComposerPasteContext={(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 onChangeText(paste.value);
343 onSelectionChange?.(paste.selection);
344 props.onPasteContext?.(paste);
345 setMostRecentEventCount(acknowledgedEventCount);
346 forceNativeEventRender((sequence) => sequence + 1);
347 }}
348 onComposerPasteText={(event) => {
349 const paste = event.nativeEvent;
350 const acknowledgedEventCount = acceptNativeEvent(
351 paste.eventCount,
352 paste.value,
353 paste.selection,
354 );
355 if (acknowledgedEventCount === false) return;
356 // Synchronize the draft before an async paste captures its insertion target.
357 // React props can still precede the last native keystroke.
358 onChangeText(paste.value);
359 onSelectionChange?.(paste.selection);
360 onPasteText?.(paste);
361 setMostRecentEventCount(acknowledgedEventCount);
362 forceNativeEventRender((sequence) => sequence + 1);
363 }}
364 onComposerFocus={onFocus}
365 onComposerBlur={onBlur}
366 />
367 </TextInputWrapper>
368 );
370​
371export type {
372 ComposerEditorHandle,
373 ComposerEditorProps,
374 ComposerEditorSelection,
375 ComposerTextPaste,
376} from "./T3ComposerEditor.types";