Skip to content
TypeScript

fix(mobile): sending on iOS no longer leaves an autocorrected draft behind (#26452)

Alex Southwell7ef841dcf7c9
diff --git a/apps/mobile/modules/t3-composer-editor/ios/T3ComposerEditorModule.swift b/apps/mobile/modules/t3-composer-editor/ios/T3ComposerEditorModule.swift
index e16582ce2b5..c54a1a84e96 100644
--- a/apps/mobile/modules/t3-composer-editor/ios/T3ComposerEditorModule.swift
+++ b/apps/mobile/modules/t3-composer-editor/ios/T3ComposerEditorModule.swift
@@ -132,6 +132,9 @@ public class T3ComposerEditorModule: Module {
AsyncFunction("setSelection") { (view: T3ComposerEditorView, start: Int, end: Int) in
view.setSelection(start: start, end: end)
}
+ AsyncFunction("readState") { (view: T3ComposerEditorView) -> [String: Any] in
+ view.readState()
+ }
}
}
}
diff --git a/apps/mobile/modules/t3-composer-editor/ios/T3ComposerEditorView.swift b/apps/mobile/modules/t3-composer-editor/ios/T3ComposerEditorView.swift
index 36e0385cd06..230aaa134c4 100644
--- a/apps/mobile/modules/t3-composer-editor/ios/T3ComposerEditorView.swift
+++ b/apps/mobile/modules/t3-composer-editor/ios/T3ComposerEditorView.swift
@@ -447,6 +447,8 @@ public final class T3ComposerEditorView: ExpoView, UITextViewDelegate, UITextDro
private var isReadOnly = false
private var isApplyingControlledValue = false
private var nativeEventCount = 0
+ // Count of the latest intercepted paste, so a flush can tell whether JS has received it.
+ private var lastPasteEventCount = 0
private var hasControlledDocument = false
private var resetGeneration = 0
private var lastContentSize = CGSize.zero
@@ -499,6 +501,7 @@ public final class T3ComposerEditorView: ExpoView, UITextViewDelegate, UITextDro
guard let self else { return }
let selection = self.sourceSelection()
self.nativeEventCount += 1
+ self.lastPasteEventCount = self.nativeEventCount
var payload: [String: Any] = context
payload["value"] = self.textView.serializedText()
payload["eventCount"] = self.nativeEventCount
@@ -510,6 +513,7 @@ public final class T3ComposerEditorView: ExpoView, UITextViewDelegate, UITextDro
guard let self else { return }
let selection = self.sourceSelection()
self.nativeEventCount += 1
+ self.lastPasteEventCount = self.nativeEventCount
self.onComposerPasteText([
"value": self.textView.serializedText(),
"eventCount": self.nativeEventCount,
@@ -677,6 +681,8 @@ public final class T3ComposerEditorView: ExpoView, UITextViewDelegate, UITextDro
}
if isReset {
resetGeneration = document.resetGeneration
+ // JS drops a paste from before the reset by generation, so the flush must not wait for it.
+ lastPasteEventCount = 0
endComposition()
}
// iOS destroys this view under display: none and mounts a fresh one while JS keeps its
@@ -807,6 +813,17 @@ public final class T3ComposerEditorView: ExpoView, UITextViewDelegate, UITextDro
textView.resignFirstResponder()
}
+ func readState() -> [String: Any] {
+ let selection = sourceSelection()
+ return [
+ "value": value,
+ "selection": ["start": selection.start, "end": selection.end],
+ "eventCount": nativeEventCount,
+ "resetGeneration": resetGeneration,
+ "pasteEventCount": lastPasteEventCount,
+ ]
+ }
+
func setSelection(start: Int, end: Int) {
let previousSelection = sourceSelection()
requestedSelection = ComposerSelectionPayload(start: start, end: end)
diff --git a/apps/mobile/src/components/ComposerEditor.ios.test.tsx b/apps/mobile/src/components/ComposerEditor.ios.test.tsx
index d3b7fa11a43..7384c5d425f 100644
--- a/apps/mobile/src/components/ComposerEditor.ios.test.tsx
+++ b/apps/mobile/src/components/ComposerEditor.ios.test.tsx
@@ -1,5 +1,13 @@
import { RegistryContext } from "@effect/atom-react";
-import { act, useLayoutEffect, useRef, type ReactNode } from "react";
+import {
+ act,
+ createRef,
+ useImperativeHandle,
+ useLayoutEffect,
+ useRef,
+ type ReactNode,
+ type Ref,
+} from "react";
import { createRoot } from "react-dom/client";
import { expect, it, vi } from "vite-plus/test";
@@ -11,6 +19,7 @@ interface NativeEvent {
}
interface NativeProps {
+ readonly ref?: Ref<unknown>;
readonly controlledDocumentJson: string;
readonly onComposerChange: (event: { readonly nativeEvent: NativeEvent }) => void;
}
@@ -20,17 +29,27 @@ const native = vi.hoisted(() => ({
text: "",
eventCount: 0,
resetGeneration: 0,
+ pasteEventCount: 0,
mounts: 0,
props: null as NativeProps | null,
deliver: null as ((event: NativeEvent) => void) | null,
}));
-function NativeView(props: NativeProps) {
+function NativeView({ ref, ...props }: NativeProps) {
const propsRef = useRef(props);
useLayoutEffect(() => {
- Object.assign(native, { text: "", eventCount: 0, resetGeneration: 0 });
+ Object.assign(native, { text: "", eventCount: 0, resetGeneration: 0, pasteEventCount: 0 });
native.mounts += 1;
}, []);
+ useImperativeHandle(ref, () => ({
+ readState: async () => ({
+ value: native.text,
+ selection: { start: native.text.length, end: native.text.length },
+ eventCount: native.eventCount,
+ resetGeneration: native.resetGeneration,
+ pasteEventCount: native.pasteEventCount,
+ }),
+ }));
useLayoutEffect(() => {
propsRef.current = props;
native.props = props;
@@ -55,6 +74,18 @@ function NativeView(props: NativeProps) {
return null;
}
+// A native edit whose event has not reached JS yet.
+function pend(value: string): NativeEvent {
+ native.eventCount += 1;
+ native.text = value;
+ return {
+ value,
+ selection: { start: value.length, end: value.length },
+ eventCount: native.eventCount,
+ resetGeneration: native.resetGeneration,
+ };
+}
+
function emit(value: string, resetGeneration = native.resetGeneration) {
native.eventCount += 1;
native.text = value;
@@ -116,13 +147,21 @@ import {
useComposerDraft,
} from "../state/use-composer-drafts";
import { ComposerEditor } from "./ComposerEditor";
+import type { ComposerEditorHandle } from "../native/T3ComposerEditor.types";
const DRAFT_KEY = "environment:thread";
-function ThreadComposer({ draftKey = DRAFT_KEY }: { draftKey?: string }) {
+function ThreadComposer({
+ draftKey = DRAFT_KEY,
+ editorRef,
+}: {
+ draftKey?: string;
+ editorRef?: Ref<ComposerEditorHandle>;
+}) {
const draft = useComposerDraft(draftKey);
return (
<ComposerEditor
+ ref={editorRef}
draftKey={draftKey}
value={draft.text}
onChangeText={(text) => setComposerDraftText(draftKey, text)}
@@ -190,3 +229,51 @@ it("keeps a pending event from the previous native editor out of the selected dr
expect(getComposerDraftSnapshot(second).text).toBe("Draft B");
expect(native.text).toBe("Draft B");
});
+
+async function renderFlushableComposer() {
+ (globalThis as { IS_REACT_ACT_ENVIRONMENT?: boolean }).IS_REACT_ACT_ENVIRONMENT = true;
+ const editor = createRef<ComposerEditorHandle>();
+ const root = createRoot(document.createElement("div"));
+ await act(async () =>
+ root.render(
+ <RegistryContext.Provider value={appAtomRegistry}>
+ <ThreadComposer editorRef={editor} />
+ </RegistryContext.Provider>,
+ ),
+ );
+ return {
+ editor,
+ [Symbol.asyncDispose]: async () => act(() => root.unmount()),
+ };
+}
+
+it("sends the autocorrection the Send tap accepted, and its late event cannot refill the draft", async () => {
+ await using screen = await renderFlushableComposer();
+ await act(async () => emit("Hello wrold"));
+ const lateCorrection = pend("Hello world");
+
+ await act(async () => screen.editor.current!.flushPendingInput());
+ expect(getComposerDraftSnapshot(DRAFT_KEY).text).toBe("Hello world");
+
+ await act(async () => {
+ clearComposerDraftContent(DRAFT_KEY);
+ native.deliver!(lateCorrection);
+ });
+ expect(getComposerDraftSnapshot(DRAFT_KEY).text).toBe("");
+});
+
+it("does not flush past a paste whose event has not reached JS", async () => {
+ await using screen = await renderFlushableComposer();
+ await act(async () => emit("Before"));
+ const paste = pend("Before pasted");
+ native.pasteEventCount = paste.eventCount;
+ const caretMove = pend("Before pasted");
+
+ await act(async () => screen.editor.current!.flushPendingInput());
+ expect(getComposerDraftSnapshot(DRAFT_KEY).text).toBe("Before");
+
+ await act(async () => native.deliver!(paste));
+ expect(getComposerDraftSnapshot(DRAFT_KEY).text).toBe("Before pasted");
+ await act(async () => native.deliver!(caretMove));
+ expect(getComposerDraftSnapshot(DRAFT_KEY).text).toBe("Before pasted");
+});
diff --git a/apps/mobile/src/features/threads/ThreadComposer.tsx b/apps/mobile/src/features/threads/ThreadComposer.tsx
index fe17a29dd47..57bda9aa98c 100644
--- a/apps/mobile/src/features/threads/ThreadComposer.tsx
+++ b/apps/mobile/src/features/threads/ThreadComposer.tsx
@@ -683,6 +683,7 @@ export const ThreadComposer = function ThreadComposer(props: ThreadComposerProps
const threadKey = scopedThreadKey(props.environmentId, props.selectedThread.id);
if (inFlightThreadIdsRef.current.has(threadKey)) return;
inFlightThreadIdsRef.current.add(threadKey);
+ await inputRef.current?.flushPendingInput();
const draftAtSend = getComposerDraftSnapshot(composerDraftKey);
const stillSendable = () => {
const draft = getComposerDraftSnapshot(composerDraftKey);
diff --git a/apps/mobile/src/native/T3ComposerEditor.ios.tsx b/apps/mobile/src/native/T3ComposerEditor.ios.tsx
index 6b1ebc939bf..03b5ab40deb 100644
--- a/apps/mobile/src/native/T3ComposerEditor.ios.tsx
+++ b/apps/mobile/src/native/T3ComposerEditor.ios.tsx
@@ -72,6 +72,13 @@ interface NativeComposerEditorRef {
focus: () => Promise<void>;
blur: () => Promise<void>;
setSelection: (start: number, end: number) => Promise<void>;
+ readState: () => Promise<{
+ readonly value: string;
+ readonly selection: ComposerEditorSelection;
+ readonly eventCount: number;
+ readonly resetGeneration: number;
+ readonly pasteEventCount: number;
+ }>;
}
interface NativeComposerEditorProps extends ViewProps {
@@ -170,17 +177,6 @@ export function ComposerEditor({
const theme = useUniwindTheme();
const fontFamily = FONT_FAMILIES.regular;
- useImperativeHandle(
- ref,
- () => ({
- focus: () => settleViewCommand(nativeRef.current?.focus()),
- blur: () => settleViewCommand(nativeRef.current?.blur()),
- setSelection: (nextSelection) =>
- settleViewCommand(nativeRef.current?.setSelection(nextSelection.start, nextSelection.end)),
- }),
- [],
- );
-
const skillLabels = useMemo(() => composerSkillLabels(skills), [skills]);
const chipTextColor = createNativeComposerTheme(theme).text;
const tokensJson = useMemo(() => {
@@ -299,6 +295,31 @@ export function ComposerEditor({
},
[nativeEventSnapshotsRef, readResetGeneration],
);
+ const applyNativeChange = (event: NativeEditorEvent["nativeEvent"]) => {
+ const acknowledgedEventCount = acceptNativeEvent(event);
+ if (acknowledgedEventCount === false) return;
+ onChangeText(event.value);
+ onSelectionChange?.(event.selection);
+ setMostRecentEventCount(acknowledgedEventCount);
+ forceNativeEventRender((sequence) => sequence + 1);
+ };
+ useImperativeHandle(ref, () => ({
+ focus: () => settleViewCommand(nativeRef.current?.focus()),
+ blur: () => settleViewCommand(nativeRef.current?.blur()),
+ setSelection: (nextSelection) =>
+ settleViewCommand(nativeRef.current?.setSelection(nextSelection.start, nextSelection.end)),
+ // Tapping outside the editor makes iOS accept a pending autocorrection, and that edit's
+ // event can reach JS after the tap's handler has already read the draft.
+ flushPendingInput: async () => {
+ const state = await Promise.resolve()
+ .then(() => nativeRef.current?.readState())
+ .catch(() => undefined);
+ // Acknowledging past a paste JS has not received yet would get the paste rejected.
+ if (state && state.pasteEventCount <= mostRecentEventCountRef.current) {
+ applyNativeChange(state);
+ }
+ },
+ }));
const themeJson = JSON.stringify(createNativeComposerTheme(theme));
const resolvedTextStyle = StyleSheet.flatten(textStyle) ?? {};
return (
@@ -334,14 +355,7 @@ export function ComposerEditor({
textPasteThresholdBytes={onPasteText ? PASTED_TEXT_ATTACHMENT_THRESHOLD_BYTES : 0}
maxInputChars={PROVIDER_SEND_TURN_MAX_INPUT_CHARS}
style={style as StyleProp<ViewStyle>}
- onComposerChange={(event) => {
- const acknowledgedEventCount = acceptNativeEvent(event.nativeEvent);
- if (acknowledgedEventCount === false) return;
- onChangeText(event.nativeEvent.value);
- onSelectionChange?.(event.nativeEvent.selection);
- setMostRecentEventCount(acknowledgedEventCount);
- forceNativeEventRender((sequence) => sequence + 1);
- }}
+ onComposerChange={(event) => applyNativeChange(event.nativeEvent)}
onComposerSelectionChange={(event) => {
const acknowledgedEventCount = acceptNativeEvent(event.nativeEvent);
if (acknowledgedEventCount === false) return;
diff --git a/apps/mobile/src/native/T3ComposerEditor.native.tsx b/apps/mobile/src/native/T3ComposerEditor.native.tsx
index e1ed9f74256..9daa11ac372 100644
--- a/apps/mobile/src/native/T3ComposerEditor.native.tsx
+++ b/apps/mobile/src/native/T3ComposerEditor.native.tsx
@@ -167,6 +167,7 @@ export function ComposerEditor({
blur: () => settleViewCommand(nativeRef.current?.blur()),
setSelection: (nextSelection) =>
settleViewCommand(nativeRef.current?.setSelection(nextSelection.start, nextSelection.end)),
+ flushPendingInput: async () => {},
}),
[],
);
diff --git a/apps/mobile/src/native/T3ComposerEditor.tsx b/apps/mobile/src/native/T3ComposerEditor.tsx
index 6428c9beeb0..fa29f3248ca 100644
--- a/apps/mobile/src/native/T3ComposerEditor.tsx
+++ b/apps/mobile/src/native/T3ComposerEditor.tsx
@@ -35,6 +35,7 @@ export function ComposerEditor({
blur: () => inputRef.current?.blur(),
setSelection: (nextSelection) =>
inputRef.current?.setSelection(nextSelection.start, nextSelection.end),
+ flushPendingInput: async () => {},
}),
[],
);
diff --git a/apps/mobile/src/native/T3ComposerEditor.types.ts b/apps/mobile/src/native/T3ComposerEditor.types.ts
index 718ecb09ba5..7c5635bd989 100644
--- a/apps/mobile/src/native/T3ComposerEditor.types.ts
+++ b/apps/mobile/src/native/T3ComposerEditor.types.ts
@@ -22,6 +22,8 @@ export interface ComposerEditorHandle {
focus: () => void;
blur: () => void;
setSelection: (selection: ComposerEditorSelection) => void;
+ /** iOS: resolves once a native edit still in flight has reached `onChangeText`. */
+ flushPendingInput: () => Promise<void>;
}
export interface ComposerEditorProps {
diff --git a/apps/mobile/src/native/composerEditorRevision.test.ts b/apps/mobile/src/native/composerEditorRevision.test.ts
index 2ddd70e1c3d..3c6e7d44626 100644
--- a/apps/mobile/src/native/composerEditorRevision.test.ts
+++ b/apps/mobile/src/native/composerEditorRevision.test.ts
@@ -164,3 +164,10 @@ describe("typing immediately before an intercepted paste", () => {
expect(acknowledgeComposerNativeEvent(2, 1)).toBeNull();
});
});
+
+describe("acknowledgeComposerNativeEvent", () => {
+ it("drops a native edit a send already read, so it cannot refill the cleared draft", () => {
+ expect(acknowledgeComposerNativeEvent(76, 77)).toBe(77);
+ expect(acknowledgeComposerNativeEvent(77, 77)).toBeNull();
+ });
+});
diff --git a/apps/mobile/src/native/composerEditorRevision.ts b/apps/mobile/src/native/composerEditorRevision.ts
index dc037b66f3d..fb8bc07efc9 100644
--- a/apps/mobile/src/native/composerEditorRevision.ts
+++ b/apps/mobile/src/native/composerEditorRevision.ts
@@ -17,7 +17,7 @@ export function acknowledgeComposerNativeEvent(
): number | null {
if (
!Number.isSafeInteger(incomingEventCount) ||
- incomingEventCount < mostRecentEventCount ||
+ incomingEventCount <= mostRecentEventCount ||
// Events from before the editor applied a parent reset describe text the parent replaced.
incomingResetGeneration < resetGeneration
) {