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

T3ComposerEditor.native.tsx

303 lines11.2 KB

1import { collectComposerInlineTokens } from "@t3tools/shared/composerInlineTokens";
2import { requireNativeView } from "expo";
3import { TextInputWrapper } from "expo-paste-input";
4import {
5 useCallback,
6 useEffect,
7 useImperativeHandle,
8 useMemo,
9 useRef,
10 useState,
11 type Ref,
12} from "react";
13import type { NativeSyntheticEvent, ViewProps } from "react-native";
14import { Image, StyleSheet } from "react-native";
15​
16import { markdownFileIconSource } from "@t3tools/mobile-markdown-text/file-icons";
17import { resolveMarkdownFileIcon } from "@t3tools/mobile-markdown-text/links";
18import { MOBILE_TYPOGRAPHY } from "../lib/typography";
19import { useNativePaste } from "../lib/useNativePaste";
20import { useFontFamily } from "../lib/useFontFamily";
21import { useAppearancePreferences } from "../features/settings/appearance/AppearancePreferencesProvider";
22import { useUniwindTheme } from "../lib/useUniwindTheme";
23import {
24 acknowledgeComposerNativeEvent,
25 assumeComposerControlledState,
26 isComposerNativeEcho,
27 pruneAcknowledgedComposerNativeEvents,
28 resolveComposerControlledEventCount,
29 type ComposerNativeEventSnapshot,
30} from "./composerEditorRevision";
31import type { ComposerEditorProps, ComposerEditorSelection } from "./T3ComposerEditor.types";
32​
33const NATIVE_MODULE_NAME = "T3ComposerEditor";
34const EMPTY_SKILLS: NonNullable<ComposerEditorProps["skills"]> = [];
35​
36type NativeEditorEvent = NativeSyntheticEvent<{
37 readonly value: string;
38 readonly selection: ComposerEditorSelection;
39 readonly eventCount: number;
40}>;
41​
42type NativeSelectionEvent = NativeSyntheticEvent<{
43 readonly value: string;
44 readonly selection: ComposerEditorSelection;
45 readonly eventCount: number;
46}>;
47​
48type NativePasteImagesEvent = NativeSyntheticEvent<{
49 readonly uris: ReadonlyArray<string>;
50}>;
51​
52interface NativeComposerEditorRef {
53 focus: () => Promise<void>;
54 blur: () => Promise<void>;
55 setSelection: (start: number, end: number) => Promise<void>;
57​
58interface NativeComposerEditorProps extends ViewProps {
59 readonly ref?: Ref<NativeComposerEditorRef>;
60 readonly controlledDocumentJson: string;
61 readonly themeJson: string;
62 readonly placeholder: string;
63 readonly fontFamily: string;
64 readonly fontSize: number;
65 readonly lineHeight: number;
66 readonly contentInsetVertical: number;
67 readonly singleLineCentered: boolean;
68 readonly editable: boolean;
69 readonly scrollEnabled: boolean;
70 readonly autoFocus: boolean;
71 readonly autoCorrect: boolean;
72 readonly spellCheck: boolean;
73 readonly onComposerChange: (event: NativeEditorEvent) => void;
74 readonly onComposerSelectionChange?: (event: NativeSelectionEvent) => void;
75 readonly onComposerPasteImages?: (event: NativePasteImagesEvent) => void;
76 readonly onComposerFocus?: () => void;
77 readonly onComposerBlur?: () => void;
79​
80const NativeView = requireNativeView<NativeComposerEditorProps>(NATIVE_MODULE_NAME);
81​
82function basename(path: string): string {
83 const separator = Math.max(path.lastIndexOf("/"), path.lastIndexOf("\\"));
84 return separator >= 0 ? path.slice(separator + 1) : path;
86​
87function fileIconUri(path: string): string {
88 return Image.resolveAssetSource(markdownFileIconSource(resolveMarkdownFileIcon(path))).uri;
90​
91export function ComposerEditor({
92 ref,
93 skills = EMPTY_SKILLS,
94 selection,
95 style,
96 textStyle,
97 onChangeText,
98 onSelectionChange,
99 onPasteImages,
100 onFocus,
101 onBlur,
102 contentInsetVertical = 0,
103 ...props
104}: ComposerEditorProps) {
105 const nativeRef = useRef<NativeComposerEditorRef>(null);
106 const mostRecentEventCountRef = useRef(0);
107 const [mostRecentEventCount, setMostRecentEventCount] = useState(0);
108 const [, forceNativeEventRender] = useState(0);
109 // The native editor mounts empty, so the snapshot history starts empty: the
110 // first controlled payload must be a non-echo so a restored draft (or a
111 // recycled native view) is applied rather than skipped.
112 const nativeEventSnapshotsRef = useRef<ComposerNativeEventSnapshot[]>([]);
113 const [initialConfirmedTokens] = useState(() => collectComposerInlineTokens(props.value));
114 const confirmedTokensRef = useRef(initialConfirmedTokens);
115 const theme = useUniwindTheme();
116 const handlePaste = useNativePaste((uris) => onPasteImages?.(uris));
117​
118 useImperativeHandle(
119 ref,
120 () => ({
121 focus: () => void nativeRef.current?.focus(),
122 blur: () => void nativeRef.current?.blur(),
123 setSelection: (nextSelection) =>
124 void nativeRef.current?.setSelection(nextSelection.start, nextSelection.end),
125 }),
126 [],
127 );
128​
129 const skillLabels = useMemo(
130 () => new Map(skills.map((skill) => [skill.name, skill.displayName?.trim() || skill.name])),
131 [skills],
132 );
133 const tokensJson = useMemo(() => {
134 const tokens = collectComposerInlineTokens(props.value, {
135 preserveTrailingFrom: confirmedTokensRef.current,
136 });
137 confirmedTokensRef.current = tokens;
138 return JSON.stringify(
139 tokens.map((token) => ({
140 type: token.type,
141 source: token.source,
142 start: token.start,
143 end: token.end,
144 label:
145 token.type === "skill"
146 ? (skillLabels.get(token.value) ?? token.value)
147 : basename(token.value),
148 iconUri: token.type === "mention" ? fileIconUri(token.value) : null,
149 })),
150 );
151 }, [props.value, skillLabels]);
152 // Every render resolves against the snapshot history, so a render whose
153 // (value, selection) lags the acknowledged native state is stamped behind
154 // the native revision and rejected by the editor instead of re-applying a
155 // stale caret or stale text mid-typing.
156 const controlledEventCount = resolveComposerControlledEventCount(
157 props.value,
158 selection ?? null,
159 mostRecentEventCount,
160 nativeEventSnapshotsRef.current,
161 );
162 const acknowledgesLatestNativeEvent = isComposerNativeEcho(
163 props.value,
164 selection ?? null,
165 mostRecentEventCount,
166 nativeEventSnapshotsRef.current,
167 );
168 const isNativeEcho =
169 controlledEventCount === mostRecentEventCount && acknowledgesLatestNativeEvent;
170 const controlledDocumentJson = JSON.stringify({
171 value: props.value,
172 selection: isNativeEcho ? null : (selection ?? null),
173 tokensJson,
174 mostRecentEventCount: controlledEventCount,
175 isNativeEcho,
176 });
177 useEffect(() => {
178 if (!acknowledgesLatestNativeEvent) return;
179 nativeEventSnapshotsRef.current = pruneAcknowledgedComposerNativeEvents(
180 nativeEventSnapshotsRef.current,
181 mostRecentEventCount,
182 );
183 }, [acknowledgesLatestNativeEvent, mostRecentEventCount]);
184 const assumedValue = props.value;
185 useEffect(() => {
186 // A native event that arrived after this render was committed moves the
187 // acknowledged revision forward; the editor rejects this payload, so the
188 // snapshot history must not assume it applied.
189 if (isNativeEcho || controlledEventCount !== mostRecentEventCountRef.current) return;
190 nativeEventSnapshotsRef.current = assumeComposerControlledState(
191 nativeEventSnapshotsRef.current,
192 controlledEventCount,
193 assumedValue,
194 );
195 }, [assumedValue, controlledEventCount, isNativeEcho, controlledDocumentJson]);
196 const acceptNativeEvent = useCallback(
197 (eventCount: number, value: string, nextSelection: ComposerEditorSelection) => {
198 const acknowledgedEventCount = acknowledgeComposerNativeEvent(
199 mostRecentEventCountRef.current,
200 eventCount,
201 );
202 if (acknowledgedEventCount === null) {
203 return false;
204 }
205 mostRecentEventCountRef.current = acknowledgedEventCount;
206 nativeEventSnapshotsRef.current.push({
207 eventCount: acknowledgedEventCount,
208 value,
209 selection: nextSelection,
210 });
211 return acknowledgedEventCount;
212 },
213 [],
214 );
215 const { systemColorsActive } = useAppearancePreferences();
216 const themeJson = JSON.stringify({
217 selection: systemColorsActive ? theme["--color-primary"] : null,
218 text: theme["--color-foreground"],
219 placeholder: theme["--color-placeholder"],
220 chipBackground: theme["--color-subtle"],
221 chipBorder: theme["--color-border"],
222 chipText: theme["--color-foreground"],
223 skillBackground: theme["--color-inline-skill-background"],
224 skillBorder: theme["--color-inline-skill-border"],
225 skillText: theme["--color-inline-skill-foreground"],
226 fileTint: theme["--color-icon-muted"],
227 });
228 const resolvedTextStyle = StyleSheet.flatten(textStyle) ?? {};
229 const regularFontFamily = useFontFamily("regular");
230 return (
231 <TextInputWrapper onPaste={handlePaste} style={[{ minHeight: 0 }, style]}>
232 <NativeView
233 ref={nativeRef}
234 controlledDocumentJson={controlledDocumentJson}
235 themeJson={themeJson}
236 placeholder={props.placeholder ?? ""}
237 fontFamily={
238 typeof resolvedTextStyle.fontFamily === "string"
239 ? resolvedTextStyle.fontFamily
240 : regularFontFamily
241 }
242 fontSize={
243 typeof resolvedTextStyle.fontSize === "number"
244 ? resolvedTextStyle.fontSize
245 : MOBILE_TYPOGRAPHY.body.fontSize
246 }
247 lineHeight={
248 typeof resolvedTextStyle.lineHeight === "number"
249 ? resolvedTextStyle.lineHeight
250 : MOBILE_TYPOGRAPHY.body.lineHeight
251 }
252 contentInsetVertical={contentInsetVertical}
253 singleLineCentered={props.singleLineCentered ?? false}
254 editable={(props.editable ?? true) && !(props.readOnly ?? false)}
255 scrollEnabled={props.scrollEnabled ?? true}
256 autoFocus={props.autoFocus ?? false}
257 autoCorrect={props.autoCorrect ?? true}
258 spellCheck={props.spellCheck ?? true}
259 style={{ flex: 1, minHeight: 0 }}
260 onComposerChange={(event) => {
261 const acknowledgedEventCount = acceptNativeEvent(
262 event.nativeEvent.eventCount,
263 event.nativeEvent.value,
264 event.nativeEvent.selection,
265 );
266 if (acknowledgedEventCount === false) return;
267 onChangeText(event.nativeEvent.value);
268 onSelectionChange?.(event.nativeEvent.selection);
269 setMostRecentEventCount(acknowledgedEventCount);
270 forceNativeEventRender((sequence) => sequence + 1);
271 }}
272 onComposerSelectionChange={(event) => {
273 const acknowledgedEventCount = acceptNativeEvent(
274 event.nativeEvent.eventCount,
275 event.nativeEvent.value,
276 event.nativeEvent.selection,
277 );
278 if (acknowledgedEventCount === false) return;
279 // Android emits the selection change mid-mutation, before the change
280 // event, so the payload can carry post-edit text. It must reach the
281 // parent alongside the acknowledged revision, or the next render
282 // stamps the stale draft at that revision and can re-apply it over
283 // the newer native text.
284 if (event.nativeEvent.value !== props.value) {
285 onChangeText(event.nativeEvent.value);
286 }
287 onSelectionChange?.(event.nativeEvent.selection);
288 setMostRecentEventCount(acknowledgedEventCount);
289 forceNativeEventRender((sequence) => sequence + 1);
290 }}
291 onComposerPasteImages={(event) => onPasteImages?.(event.nativeEvent.uris)}
292 onComposerFocus={onFocus}
293 onComposerBlur={onBlur}
294 />
295 </TextInputWrapper>
296 );
298​
299export type {
300 ComposerEditorHandle,
301 ComposerEditorProps,
302 ComposerEditorSelection,
303} from "./T3ComposerEditor.types";