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

T3ComposerEditor.ios.tsx

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