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

T3ComposerEditor.native.tsx

286 lines9.9 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 { MOBILE_TYPOGRAPHY } from "../lib/typography";
18import { useFontFamily } from "../lib/useFontFamily";
19import { useThemeColor } from "../lib/useThemeColor";
20import {
21 acknowledgeComposerNativeEvent,
22 isComposerNativeEcho,
23 pruneAcknowledgedComposerNativeEvents,
24 resolveComposerControlledEventCount,
25 type ComposerNativeEventSnapshot,
26} from "./composerEditorRevision";
27import type { ComposerEditorProps, ComposerEditorSelection } from "./T3ComposerEditor.types";
28​
29const NATIVE_MODULE_NAME = "T3ComposerEditor";
30const EMPTY_SKILLS: NonNullable<ComposerEditorProps["skills"]> = [];
31​
32type NativeEditorEvent = NativeSyntheticEvent<{
33 readonly value: string;
34 readonly selection: ComposerEditorSelection;
35 readonly eventCount: number;
36}>;
37​
38type NativeSelectionEvent = NativeSyntheticEvent<{
39 readonly value: string;
40 readonly selection: ComposerEditorSelection;
41 readonly eventCount: number;
42}>;
43​
44type NativePasteImagesEvent = NativeSyntheticEvent<{
45 readonly uris: ReadonlyArray<string>;
46}>;
47​
48interface NativeComposerEditorRef {
49 focus: () => Promise<void>;
50 blur: () => Promise<void>;
51 setSelection: (start: number, end: number) => Promise<void>;
53​
54interface NativeComposerEditorProps extends ViewProps {
55 readonly ref?: Ref<NativeComposerEditorRef>;
56 readonly controlledDocumentJson: string;
57 readonly themeJson: string;
58 readonly placeholder: string;
59 readonly fontFamily: string;
60 readonly fontSize: number;
61 readonly lineHeight: number;
62 readonly contentInsetVertical: number;
63 readonly singleLineCentered: boolean;
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;
75​
76const NativeView = requireNativeView<NativeComposerEditorProps>(NATIVE_MODULE_NAME);
77​
78function basename(path: string): string {
79 const separator = Math.max(path.lastIndexOf("/"), path.lastIndexOf("\\"));
80 return separator >= 0 ? path.slice(separator + 1) : path;
82​
83function fileIconUri(path: string): string {
84 return Image.resolveAssetSource(markdownFileIconSource(resolveMarkdownFileIcon(path))).uri;
86​
87export function ComposerEditor({
88 ref,
89 skills = EMPTY_SKILLS,
90 selection,
91 style,
92 textStyle,
93 onChangeText,
94 onSelectionChange,
95 onPasteImages,
96 onFocus,
97 onBlur,
98 contentInsetVertical = 0,
99 ...props
100}: ComposerEditorProps) {
101 const nativeRef = useRef<NativeComposerEditorRef>(null);
102 const mostRecentEventCountRef = useRef(0);
103 const [mostRecentEventCount, setMostRecentEventCount] = useState(0);
104 const [nativeEventSequence, setNativeEventSequence] = useState(0);
105 const previousRenderedEventSequenceRef = useRef(0);
106 const nativeEventSnapshotsRef = useRef<ComposerNativeEventSnapshot[]>([
107 { eventCount: 0, value: props.value, selection: selection ?? null },
108 ]);
109 const [initialConfirmedTokens] = useState(() => collectComposerInlineTokens(props.value));
110 const confirmedTokensRef = useRef(initialConfirmedTokens);
111 const textColor = useThemeColor("--color-foreground");
112 const placeholderColor = useThemeColor("--color-placeholder");
113 const chipBackground = useThemeColor("--color-subtle");
114 const chipBorder = useThemeColor("--color-border");
115 const chipText = useThemeColor("--color-foreground");
116 const skillBackground = useThemeColor("--color-inline-skill-background");
117 const skillBorder = useThemeColor("--color-inline-skill-border");
118 const skillText = useThemeColor("--color-inline-skill-foreground");
119 const fileTint = useThemeColor("--color-icon-muted");
120​
121 useImperativeHandle(
122 ref,
123 () => ({
124 focus: () => void nativeRef.current?.focus(),
125 blur: () => void nativeRef.current?.blur(),
126 setSelection: (nextSelection) =>
127 void nativeRef.current?.setSelection(nextSelection.start, nextSelection.end),
128 }),
129 [],
130 );
131​
132 const skillLabels = useMemo(
133 () => new Map(skills.map((skill) => [skill.name, skill.displayName?.trim() || skill.name])),
134 [skills],
135 );
136 const tokensJson = useMemo(() => {
137 const tokens = collectComposerInlineTokens(props.value, {
138 preserveTrailingFrom: confirmedTokensRef.current,
139 });
140 confirmedTokensRef.current = tokens;
141 return JSON.stringify(
142 tokens.map((token) => ({
143 type: token.type,
144 source: token.source,
145 start: token.start,
146 end: token.end,
147 label:
148 token.type === "skill"
149 ? (skillLabels.get(token.value) ?? token.value)
150 : basename(token.value),
151 iconUri: token.type === "mention" ? fileIconUri(token.value) : null,
152 })),
153 );
154 }, [props.value, skillLabels]);
155 const includesNativeEvent = nativeEventSequence !== previousRenderedEventSequenceRef.current;
156 const controlledEventCount = includesNativeEvent
157 ? resolveComposerControlledEventCount(
158 props.value,
159 selection ?? null,
160 mostRecentEventCount,
161 nativeEventSnapshotsRef.current,
162 )
163 : mostRecentEventCount;
164 const acknowledgesLatestNativeEvent = isComposerNativeEcho(
165 props.value,
166 selection ?? null,
167 mostRecentEventCount,
168 nativeEventSnapshotsRef.current,
169 );
170 const isNativeEcho =
171 includesNativeEvent &&
172 controlledEventCount === mostRecentEventCount &&
173 acknowledgesLatestNativeEvent;
174 const controlledDocumentJson = JSON.stringify({
175 value: props.value,
176 selection: isNativeEcho ? null : (selection ?? null),
177 tokensJson,
178 mostRecentEventCount: controlledEventCount,
179 isNativeEcho,
180 });
181 useEffect(() => {
182 previousRenderedEventSequenceRef.current = nativeEventSequence;
183 }, [nativeEventSequence]);
184 useEffect(() => {
185 if (!acknowledgesLatestNativeEvent) return;
186 nativeEventSnapshotsRef.current = pruneAcknowledgedComposerNativeEvents(
187 nativeEventSnapshotsRef.current,
188 mostRecentEventCount,
189 );
190 }, [acknowledgesLatestNativeEvent, mostRecentEventCount]);
191 const acceptNativeEvent = useCallback(
192 (eventCount: number, value: string, nextSelection: ComposerEditorSelection) => {
193 const acknowledgedEventCount = acknowledgeComposerNativeEvent(
194 mostRecentEventCountRef.current,
195 eventCount,
196 );
197 if (acknowledgedEventCount === null) {
198 return false;
199 }
200 mostRecentEventCountRef.current = acknowledgedEventCount;
201 nativeEventSnapshotsRef.current.push({
202 eventCount: acknowledgedEventCount,
203 value,
204 selection: nextSelection,
205 });
206 return acknowledgedEventCount;
207 },
208 [],
209 );
210 const themeJson = JSON.stringify({
211 text: String(textColor),
212 placeholder: String(placeholderColor),
213 chipBackground: String(chipBackground),
214 chipBorder: String(chipBorder),
215 chipText: String(chipText),
216 skillBackground: String(skillBackground),
217 skillBorder: String(skillBorder),
218 skillText: String(skillText),
219 fileTint: String(fileTint),
220 });
221 const resolvedTextStyle = StyleSheet.flatten(textStyle) ?? {};
222 const regularFontFamily = useFontFamily("regular");
223 return (
224 <NativeView
225 ref={nativeRef}
226 controlledDocumentJson={controlledDocumentJson}
227 themeJson={themeJson}
228 placeholder={props.placeholder ?? ""}
229 fontFamily={
230 typeof resolvedTextStyle.fontFamily === "string"
231 ? resolvedTextStyle.fontFamily
232 : regularFontFamily
233 }
234 fontSize={
235 typeof resolvedTextStyle.fontSize === "number"
236 ? resolvedTextStyle.fontSize
237 : MOBILE_TYPOGRAPHY.body.fontSize
238 }
239 lineHeight={
240 typeof resolvedTextStyle.lineHeight === "number"
241 ? resolvedTextStyle.lineHeight
242 : MOBILE_TYPOGRAPHY.body.lineHeight
243 }
244 contentInsetVertical={contentInsetVertical}
245 singleLineCentered={props.singleLineCentered ?? false}
246 editable={props.editable ?? true}
247 scrollEnabled={props.scrollEnabled ?? true}
248 autoFocus={props.autoFocus ?? false}
249 autoCorrect={props.autoCorrect ?? true}
250 spellCheck={props.spellCheck ?? true}
251 style={style as StyleProp<ViewStyle>}
252 onComposerChange={(event) => {
253 const acknowledgedEventCount = acceptNativeEvent(
254 event.nativeEvent.eventCount,
255 event.nativeEvent.value,
256 event.nativeEvent.selection,
257 );
258 if (acknowledgedEventCount === false) return;
259 onChangeText(event.nativeEvent.value);
260 onSelectionChange?.(event.nativeEvent.selection);
261 setMostRecentEventCount(acknowledgedEventCount);
262 setNativeEventSequence((sequence) => sequence + 1);
263 }}
264 onComposerSelectionChange={(event) => {
265 const acknowledgedEventCount = acceptNativeEvent(
266 event.nativeEvent.eventCount,
267 event.nativeEvent.value,
268 event.nativeEvent.selection,
269 );
270 if (acknowledgedEventCount === false) return;
271 onSelectionChange?.(event.nativeEvent.selection);
272 setMostRecentEventCount(acknowledgedEventCount);
273 setNativeEventSequence((sequence) => sequence + 1);
274 }}
275 onComposerPasteImages={(event) => onPasteImages?.(event.nativeEvent.uris)}
276 onComposerFocus={onFocus}
277 onComposerBlur={onBlur}
278 />
279 );
281​
282export type {
283 ComposerEditorHandle,
284 ComposerEditorProps,
285 ComposerEditorSelection,
286} from "./T3ComposerEditor.types";