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

ComposerEditor.ios.test.tsx

280 lines9.9 KB

1import { RegistryContext } from "@effect/atom-react";
2import {
3 act,
4 createRef,
5 useImperativeHandle,
6 useLayoutEffect,
7 useRef,
8 type ReactNode,
9 type Ref,
10} from "react";
11import { createRoot } from "react-dom/client";
12import { expect, it, vi } from "vite-plus/test";
13​
14interface NativeEvent {
15 readonly value: string;
16 readonly selection: { readonly start: number; readonly end: number };
17 readonly eventCount: number;
18 readonly resetGeneration: number;
20​
21interface NativeProps {
22 readonly ref?: Ref<unknown>;
23 readonly controlledDocumentJson: string;
24 readonly onComposerChange: (event: { readonly nativeEvent: NativeEvent }) => void;
26​
27// Mirrors the iOS editor's revision and reset bookkeeping (T3ComposerEditorView.setControlledDocumentJson).
28const native = vi.hoisted(() => ({
29 text: "",
30 eventCount: 0,
31 resetGeneration: 0,
32 pasteEventCount: 0,
33 mounts: 0,
34 props: null as NativeProps | null,
35 deliver: null as ((event: NativeEvent) => void) | null,
36}));
37​
38function NativeView({ ref, ...props }: NativeProps) {
39 const propsRef = useRef(props);
40 useLayoutEffect(() => {
41 Object.assign(native, { text: "", eventCount: 0, resetGeneration: 0, pasteEventCount: 0 });
42 native.mounts += 1;
43 }, []);
44 useImperativeHandle(ref, () => ({
45 readState: async () => ({
46 value: native.text,
47 selection: { start: native.text.length, end: native.text.length },
48 eventCount: native.eventCount,
49 resetGeneration: native.resetGeneration,
50 pasteEventCount: native.pasteEventCount,
51 }),
52 }));
53 useLayoutEffect(() => {
54 propsRef.current = props;
55 native.props = props;
56 native.deliver = (event) => propsRef.current.onComposerChange({ nativeEvent: event });
57 });
58 const { controlledDocumentJson } = props;
59 useLayoutEffect(() => {
60 const document = JSON.parse(controlledDocumentJson) as {
61 value: string;
62 mostRecentEventCount: number;
63 resetGeneration?: number;
64 };
65 const resetGeneration = document.resetGeneration ?? 0;
66 const isReset = resetGeneration > native.resetGeneration;
67 if (!isReset && document.mostRecentEventCount < native.eventCount) return;
68 if (isReset) {
69 native.resetGeneration = resetGeneration;
70 native.eventCount = document.mostRecentEventCount;
71 }
72 native.text = document.value;
73 }, [controlledDocumentJson]);
74 return null;
76​
77// A native edit whose event has not reached JS yet.
78function pend(value: string): NativeEvent {
79 native.eventCount += 1;
80 native.text = value;
81 return {
82 value,
83 selection: { start: value.length, end: value.length },
84 eventCount: native.eventCount,
85 resetGeneration: native.resetGeneration,
86 };
88​
89function emit(value: string, resetGeneration = native.resetGeneration) {
90 native.eventCount += 1;
91 native.text = value;
92 native.props!.onComposerChange({
93 nativeEvent: {
94 value,
95 selection: { start: value.length, end: value.length },
96 eventCount: native.eventCount,
97 resetGeneration,
98 },
99 });
101​
102vi.mock("expo", () => ({ requireNativeView: () => NativeView }));
103// Vite resolves the platform-neutral module; the race lives in the iOS editor.
104vi.mock("../native/T3ComposerEditor", () => import("../native/T3ComposerEditor.ios"));
105vi.mock("react-native", () => ({ StyleSheet: { flatten: (style: unknown) => style } }));
106vi.mock("expo-file-system", () => ({
107 Directory: class {
108 create() {}
109 },
110 File: class {
111 exists = false;
112 write() {}
113 },
114 Paths: { document: { uri: "file:///documents" } },
115}));
116vi.mock("./ui/Dialog", () => ({ alert: vi.fn() }));
117vi.mock("./ui/AppText", () => ({ AppText: ({ children }: { children?: ReactNode }) => children }));
118vi.mock("./ComposerContextSheet", () => ({ ComposerContextSheet: () => null }));
119vi.mock("../features/threads/useOpenLinkedThread", () => ({ useOpenLinkedThread: () => vi.fn() }));
120vi.mock("../state/peerLinks", () => ({ useLinkedEnvironments: () => [] }));
121vi.mock("../state/model-mentions", () => ({ useModelMentions: () => [] }));
122vi.mock("../state/preferences", async () => {
123 const { Atom } = await import("effect/reactivity");
124 return { mobilePreferencesAtom: Atom.make({ _tag: "Initial" }) };
125});
126vi.mock("../lib/composerContextClipboard", () => ({ importComposerContextClipboard: vi.fn() }));
127vi.mock("../lib/useUniwindTheme", () => ({ useUniwindTheme: () => ({}) }));
128vi.mock("../lib/nativeComposerTheme", () => ({ createNativeComposerTheme: () => ({}) }));
129vi.mock("../lib/contextChipIconSource", () => ({ contextChipIconUri: () => "" }));
130vi.mock("../features/settings/appearance/useScaledTextRole", () => ({
131 useScaledTextRole: () => ({ fontSize: 16, lineHeight: 22 }),
132}));
133vi.mock("../lib/uuid", () => ({ uuidv4: () => "uuid", randomHex: () => "0000" }));
134vi.mock("../state/assets", () => ({ assetEnvironment: {} }));
135vi.mock("../state/attachments", () => ({ attachmentEnvironment: {} }));
136vi.mock("../state/session", () => ({ environmentSession: {} }));
137vi.mock("@t3tools/client-runtime/state/runtime", () => ({
138 createEnvironmentRpcCommand: () => Symbol("rpc-command"),
139 settlePromise: vi.fn(),
140 squashAtomCommandFailure: vi.fn(),
141}));
142​
143import { appAtomRegistry } from "../state/atom-registry";
144import {
145 clearComposerDraftContent,
146 getComposerDraftSnapshot,
147 setComposerDraftText,
148 useComposerDraft,
149} from "../state/use-composer-drafts";
150import { ComposerEditor } from "./ComposerEditor";
151import type { ComposerEditorHandle } from "../native/T3ComposerEditor.types";
152​
153const DRAFT_KEY = "environment:thread";
154​
155function ThreadComposer({
156 draftKey = DRAFT_KEY,
157 editorRef,
158}: {
159 draftKey?: string;
160 editorRef?: Ref<ComposerEditorHandle>;
161}) {
162 const draft = useComposerDraft(draftKey);
163 return (
164 <ComposerEditor
165 ref={editorRef}
166 draftKey={draftKey}
167 value={draft.text}
168 onChangeText={(text) => setComposerDraftText(draftKey, text)}
169 />
170 );
172​
173it("keeps a sent draft cleared when an autocorrection lands in the same batch as the send", async () => {
174 (globalThis as { IS_REACT_ACT_ENVIRONMENT?: boolean }).IS_REACT_ACT_ENVIRONMENT = true;
175 Object.assign(native, { text: "", eventCount: 0, resetGeneration: 0, props: null });
176 const root = createRoot(document.createElement("div"));
177 await using _root = { [Symbol.asyncDispose]: async () => act(() => root.unmount()) };
178 await act(async () =>
179 root.render(
180 <RegistryContext.Provider value={appAtomRegistry}>
181 <ThreadComposer />
182 </RegistryContext.Provider>,
183 ),
184 );
185​
186 await act(async () => emit("Hello wrold"));
187 expect(getComposerDraftSnapshot(DRAFT_KEY).text).toBe("Hello wrold");
188​
189 // Send clears the draft; iOS commits the pending autocorrection as the keyboard dismisses.
190 await act(async () => {
191 clearComposerDraftContent(DRAFT_KEY);
192 emit("Hello world");
193 });
194 expect(getComposerDraftSnapshot(DRAFT_KEY).text).toBe("");
195 expect(native.text).toBe("");
196​
197 await act(async () => emit("n"));
198 expect(getComposerDraftSnapshot(DRAFT_KEY).text).toBe("n");
199 expect(native.text).toBe("n");
200});
201​
202it("keeps a pending event from the previous native editor out of the selected draft", async () => {
203 (globalThis as { IS_REACT_ACT_ENVIRONMENT?: boolean }).IS_REACT_ACT_ENVIRONMENT = true;
204 const first = "switch-draft:first";
205 const second = "switch-draft:second";
206 setComposerDraftText(first, "Draft A");
207 setComposerDraftText(second, "Draft B");
208 const root = createRoot(document.createElement("div"));
209 await using _root = { [Symbol.asyncDispose]: async () => act(() => root.unmount()) };
210 const renderDraft = (draftKey: string) =>
211 root.render(
212 <RegistryContext.Provider value={appAtomRegistry}>
213 <ThreadComposer draftKey={draftKey} />
214 </RegistryContext.Provider>,
215 );
216 await act(async () => renderDraft(first));
217 const deliverPendingEvent = native.deliver!;
218 const pending = { eventCount: native.eventCount + 1, resetGeneration: native.resetGeneration };
219 const mounts = native.mounts;
220 await act(async () => renderDraft(second));
221 // Remounting the native view would drop the keyboard mid-edit.
222 expect(native.mounts).toBe(mounts);
223 await act(async () =>
224 deliverPendingEvent({
225 value: "Draft A corrected",
226 selection: { start: 17, end: 17 },
227 ...pending,
228 }),
229 );
230 expect(getComposerDraftSnapshot(second).text).toBe("Draft B");
231 expect(native.text).toBe("Draft B");
232});
233​
234async function renderFlushableComposer() {
235 (globalThis as { IS_REACT_ACT_ENVIRONMENT?: boolean }).IS_REACT_ACT_ENVIRONMENT = true;
236 const editor = createRef<ComposerEditorHandle>();
237 const root = createRoot(document.createElement("div"));
238 await act(async () =>
239 root.render(
240 <RegistryContext.Provider value={appAtomRegistry}>
241 <ThreadComposer editorRef={editor} />
242 </RegistryContext.Provider>,
243 ),
244 );
245 return {
246 editor,
247 [Symbol.asyncDispose]: async () => act(() => root.unmount()),
248 };
250​
251it("sends the autocorrection the Send tap accepted, and its late event cannot refill the draft", async () => {
252 await using screen = await renderFlushableComposer();
253 await act(async () => emit("Hello wrold"));
254 const lateCorrection = pend("Hello world");
255​
256 await act(async () => screen.editor.current!.flushPendingInput());
257 expect(getComposerDraftSnapshot(DRAFT_KEY).text).toBe("Hello world");
258​
259 await act(async () => {
260 clearComposerDraftContent(DRAFT_KEY);
261 native.deliver!(lateCorrection);
262 });
263 expect(getComposerDraftSnapshot(DRAFT_KEY).text).toBe("");
264});
265​
266it("does not flush past a paste whose event has not reached JS", async () => {
267 await using screen = await renderFlushableComposer();
268 await act(async () => emit("Before"));
269 const paste = pend("Before pasted");
270 native.pasteEventCount = paste.eventCount;
271 const caretMove = pend("Before pasted");
272​
273 await act(async () => screen.editor.current!.flushPendingInput());
274 expect(getComposerDraftSnapshot(DRAFT_KEY).text).toBe("Before");
275​
276 await act(async () => native.deliver!(paste));
277 expect(getComposerDraftSnapshot(DRAFT_KEY).text).toBe("Before pasted");
278 await act(async () => native.deliver!(caretMove));
279 expect(getComposerDraftSnapshot(DRAFT_KEY).text).toBe("Before pasted");
280});