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

T3ComposerEditor.ios.tsx

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