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

T3ComposerEditor.ios.tsx

295 lines10.5 KB

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