fix(mobile): preserve keyboard suggestions while typing (#6323)

Co-authored-by: Claude Fable 5 <[email protected]>
This commit is contained in:
Julius MarmingeandClaude Fable 5 authored and GitHub committed 2026-08-14 10:45:43 +02:00
1 parent 6ae44b418a
commit b3b4b57794
6 files changed
+242 -53

No files matched your search

@@ -252,6 +252,9 @@ class T3ComposerEditorView(context: Context, appContext: AppContext) : ExpoView(
val textLength = editor.text?.length ?: 0
val safeStart = start.coerceIn(0, textLength)
val safeEnd = end.coerceIn(0, textLength)
// Re-applying an unchanged selection resets the keyboard's suggestion
// state, so a no-op assignment must be skipped.
if (editor.selectionStart == safeStart && editor.selectionEnd == safeEnd) return
editor.setSelection(safeStart, safeEnd)
}
@@ -281,6 +284,10 @@ class T3ComposerEditorView(context: Context, appContext: AppContext) : ExpoView(
)
private fun emitSelectionChange(start: Int, end: Int) {
// Caret moves advance the revision counter like text edits do: a
// controlled payload computed before this move is stale and must fail the
// revision guard instead of yanking the caret back mid-typing.
nativeEventCount += 1
onComposerSelectionChange(
mapOf(
"value" to editor.text.toString(),
@@ -489,6 +489,12 @@ public final class T3ComposerEditorView: ExpoView, UITextViewDelegate, UITextDro
return
}
restoreBaseTypingAttributes()
// UIKit moves the selection before textViewDidChange runs. Emitting here
// would pair the post-edit text with a pre-edit revision counter, so let
// the change event that follows carry both; only pure caret moves emit.
guard self.textView.serializedText() == value else {
return
}
emitSelection()
}
@@ -774,8 +780,12 @@ public final class T3ComposerEditorView: ExpoView, UITextViewDelegate, UITextDro
}
private func emitSelection() {
// Caret moves advance the revision counter like text edits do: a
// controlled payload computed before this move is stale and must fail the
// revision guard instead of yanking the caret back mid-typing.
let currentValue = textView.serializedText()
let selection = sourceSelection()
nativeEventCount += 1
onComposerSelectionChange([
"value": currentValue,
"selection": ["start": selection.start, "end": selection.end],
@@ -817,10 +827,16 @@ public final class T3ComposerEditorView: ExpoView, UITextViewDelegate, UITextDro
NSMaxRange(nextRange) <= textView.attributedText.length else {
return
}
self.requestedSelection = nil
// Programmatically assigning selectedRange resets the keyboard's
// autocorrect and predictive-text context even when the range is
// unchanged, so a no-op assignment must be skipped.
guard !NSEqualRanges(nextRange, textView.selectedRange) else {
return
}
isApplyingControlledValue = true
textView.selectedRange = nextRange
isApplyingControlledValue = false
self.requestedSelection = nil
}
private func updatePlaceholderVisibility() {
+38 -22
View File
@@ -19,6 +19,7 @@ import { useFontFamily } from "../lib/useFontFamily";
import { useScaledTextRole } from "../features/settings/appearance/useScaledTextRole";
import {
acknowledgeComposerNativeEvent,
assumeComposerControlledState,
isComposerNativeEcho,
pruneAcknowledgedComposerNativeEvents,
resolveComposerControlledEventCount,
@@ -102,11 +103,11 @@ export function ComposerEditor({
const nativeRef = useRef<NativeComposerEditorRef>(null);
const mostRecentEventCountRef = useRef(0);
const [mostRecentEventCount, setMostRecentEventCount] = useState(0);
const [nativeEventSequence, setNativeEventSequence] = useState(0);
const previousRenderedEventSequenceRef = useRef(0);
const nativeEventSnapshotsRef = useRef<ComposerNativeEventSnapshot[]>([
{ eventCount: 0, value: props.value, selection: selection ?? null },
]);
const [, forceNativeEventRender] = useState(0);
// The native editor mounts empty, so the snapshot history starts empty: the
// first controlled payload must be a non-echo so a restored draft (or a
// recycled native view) is applied rather than skipped.
const nativeEventSnapshotsRef = useRef<ComposerNativeEventSnapshot[]>([]);
const confirmedTokensRef = useRef(collectComposerInlineTokens(props.value));
const bodyText = useScaledTextRole("body");
const textColor = useThemeColor("--color-foreground");
@@ -154,15 +155,16 @@ export function ComposerEditor({
})),
);
}, [props.value, skillLabels]);
const includesNativeEvent = nativeEventSequence !== previousRenderedEventSequenceRef.current;
const controlledEventCount = includesNativeEvent
? resolveComposerControlledEventCount(
props.value,
selection ?? null,
mostRecentEventCount,
nativeEventSnapshotsRef.current,
)
: mostRecentEventCount;
// Every render resolves against the snapshot history, so a render whose
// (value, selection) lags the acknowledged native state is stamped behind
// the native revision and rejected by the editor instead of re-applying a
// stale caret or stale text mid-typing.
const controlledEventCount = resolveComposerControlledEventCount(
props.value,
selection ?? null,
mostRecentEventCount,
nativeEventSnapshotsRef.current,
);
const acknowledgesLatestNativeEvent = isComposerNativeEcho(
props.value,
selection ?? null,
@@ -170,9 +172,7 @@ export function ComposerEditor({
nativeEventSnapshotsRef.current,
);
const isNativeEcho =
includesNativeEvent &&
controlledEventCount === mostRecentEventCount &&
acknowledgesLatestNativeEvent;
controlledEventCount === mostRecentEventCount && acknowledgesLatestNativeEvent;
const controlledDocumentJson = JSON.stringify({
value: props.value,
selection: isNativeEcho ? null : (selection ?? null),
@@ -180,9 +180,6 @@ export function ComposerEditor({
mostRecentEventCount: controlledEventCount,
isNativeEcho,
});
useEffect(() => {
previousRenderedEventSequenceRef.current = nativeEventSequence;
}, [nativeEventSequence]);
useEffect(() => {
if (!acknowledgesLatestNativeEvent) return;
nativeEventSnapshotsRef.current = pruneAcknowledgedComposerNativeEvents(
@@ -190,6 +187,18 @@ export function ComposerEditor({
mostRecentEventCount,
);
}, [acknowledgesLatestNativeEvent, mostRecentEventCount]);
const assumedValue = props.value;
useEffect(() => {
// A native event that arrived after this render was committed moves the
// acknowledged revision forward; the editor rejects this payload, so the
// snapshot history must not assume it applied.
if (isNativeEcho || controlledEventCount !== mostRecentEventCountRef.current) return;
nativeEventSnapshotsRef.current = assumeComposerControlledState(
nativeEventSnapshotsRef.current,
controlledEventCount,
assumedValue,
);
}, [assumedValue, controlledEventCount, isNativeEcho, controlledDocumentJson]);
const acceptNativeEvent = useCallback(
(eventCount: number, value: string, nextSelection: ComposerEditorSelection) => {
const acknowledgedEventCount = acknowledgeComposerNativeEvent(
@@ -257,7 +266,7 @@ export function ComposerEditor({
onChangeText(event.nativeEvent.value);
onSelectionChange?.(event.nativeEvent.selection);
setMostRecentEventCount(acknowledgedEventCount);
setNativeEventSequence((sequence) => sequence + 1);
forceNativeEventRender((sequence) => sequence + 1);
}}
onComposerSelectionChange={(event) => {
const acknowledgedEventCount = acceptNativeEvent(
@@ -266,9 +275,16 @@ export function ComposerEditor({
event.nativeEvent.selection,
);
if (acknowledgedEventCount === false) return;
// A selection change that raced a text mutation can carry post-edit
// text. It must reach the parent alongside the acknowledged revision,
// or the next render stamps the stale draft at that revision and can
// re-apply it over the newer native text.
if (event.nativeEvent.value !== props.value) {
onChangeText(event.nativeEvent.value);
}
onSelectionChange?.(event.nativeEvent.selection);
setMostRecentEventCount(acknowledgedEventCount);
setNativeEventSequence((sequence) => sequence + 1);
forceNativeEventRender((sequence) => sequence + 1);
}}
onComposerPasteImages={(event) => onPasteImages?.(event.nativeEvent.uris)}
onComposerFocus={onFocus}
@@ -21,6 +21,7 @@ import { useFontFamily } from "../lib/useFontFamily";
import { useThemeColor } from "../lib/useThemeColor";
import {
acknowledgeComposerNativeEvent,
assumeComposerControlledState,
isComposerNativeEcho,
pruneAcknowledgedComposerNativeEvents,
resolveComposerControlledEventCount,
@@ -103,11 +104,11 @@ export function ComposerEditor({
const nativeRef = useRef<NativeComposerEditorRef>(null);
const mostRecentEventCountRef = useRef(0);
const [mostRecentEventCount, setMostRecentEventCount] = useState(0);
const [nativeEventSequence, setNativeEventSequence] = useState(0);
const previousRenderedEventSequenceRef = useRef(0);
const nativeEventSnapshotsRef = useRef<ComposerNativeEventSnapshot[]>([
{ eventCount: 0, value: props.value, selection: selection ?? null },
]);
const [, forceNativeEventRender] = useState(0);
// The native editor mounts empty, so the snapshot history starts empty: the
// first controlled payload must be a non-echo so a restored draft (or a
// recycled native view) is applied rather than skipped.
const nativeEventSnapshotsRef = useRef<ComposerNativeEventSnapshot[]>([]);
const [initialConfirmedTokens] = useState(() => collectComposerInlineTokens(props.value));
const confirmedTokensRef = useRef(initialConfirmedTokens);
const textColor = useThemeColor("--color-foreground");
@@ -155,15 +156,16 @@ export function ComposerEditor({
})),
);
}, [props.value, skillLabels]);
const includesNativeEvent = nativeEventSequence !== previousRenderedEventSequenceRef.current;
const controlledEventCount = includesNativeEvent
? resolveComposerControlledEventCount(
props.value,
selection ?? null,
mostRecentEventCount,
nativeEventSnapshotsRef.current,
)
: mostRecentEventCount;
// Every render resolves against the snapshot history, so a render whose
// (value, selection) lags the acknowledged native state is stamped behind
// the native revision and rejected by the editor instead of re-applying a
// stale caret or stale text mid-typing.
const controlledEventCount = resolveComposerControlledEventCount(
props.value,
selection ?? null,
mostRecentEventCount,
nativeEventSnapshotsRef.current,
);
const acknowledgesLatestNativeEvent = isComposerNativeEcho(
props.value,
selection ?? null,
@@ -171,9 +173,7 @@ export function ComposerEditor({
nativeEventSnapshotsRef.current,
);
const isNativeEcho =
includesNativeEvent &&
controlledEventCount === mostRecentEventCount &&
acknowledgesLatestNativeEvent;
controlledEventCount === mostRecentEventCount && acknowledgesLatestNativeEvent;
const controlledDocumentJson = JSON.stringify({
value: props.value,
selection: isNativeEcho ? null : (selection ?? null),
@@ -181,9 +181,6 @@ export function ComposerEditor({
mostRecentEventCount: controlledEventCount,
isNativeEcho,
});
useEffect(() => {
previousRenderedEventSequenceRef.current = nativeEventSequence;
}, [nativeEventSequence]);
useEffect(() => {
if (!acknowledgesLatestNativeEvent) return;
nativeEventSnapshotsRef.current = pruneAcknowledgedComposerNativeEvents(
@@ -191,6 +188,18 @@ export function ComposerEditor({
mostRecentEventCount,
);
}, [acknowledgesLatestNativeEvent, mostRecentEventCount]);
const assumedValue = props.value;
useEffect(() => {
// A native event that arrived after this render was committed moves the
// acknowledged revision forward; the editor rejects this payload, so the
// snapshot history must not assume it applied.
if (isNativeEcho || controlledEventCount !== mostRecentEventCountRef.current) return;
nativeEventSnapshotsRef.current = assumeComposerControlledState(
nativeEventSnapshotsRef.current,
controlledEventCount,
assumedValue,
);
}, [assumedValue, controlledEventCount, isNativeEcho, controlledDocumentJson]);
const acceptNativeEvent = useCallback(
(eventCount: number, value: string, nextSelection: ComposerEditorSelection) => {
const acknowledgedEventCount = acknowledgeComposerNativeEvent(
@@ -263,7 +272,7 @@ export function ComposerEditor({
onChangeText(event.nativeEvent.value);
onSelectionChange?.(event.nativeEvent.selection);
setMostRecentEventCount(acknowledgedEventCount);
setNativeEventSequence((sequence) => sequence + 1);
forceNativeEventRender((sequence) => sequence + 1);
}}
onComposerSelectionChange={(event) => {
const acknowledgedEventCount = acceptNativeEvent(
@@ -272,9 +281,17 @@ export function ComposerEditor({
event.nativeEvent.selection,
);
if (acknowledgedEventCount === false) return;
// Android emits the selection change mid-mutation, before the change
// event, so the payload can carry post-edit text. It must reach the
// parent alongside the acknowledged revision, or the next render
// stamps the stale draft at that revision and can re-apply it over
// the newer native text.
if (event.nativeEvent.value !== props.value) {
onChangeText(event.nativeEvent.value);
}
onSelectionChange?.(event.nativeEvent.selection);
setMostRecentEventCount(acknowledgedEventCount);
setNativeEventSequence((sequence) => sequence + 1);
forceNativeEventRender((sequence) => sequence + 1);
}}
onComposerPasteImages={(event) => onPasteImages?.(event.nativeEvent.uris)}
onComposerFocus={onFocus}
@@ -2,6 +2,7 @@ import { describe, expect, it } from "@effect/vitest";
import {
acknowledgeComposerNativeEvent,
assumeComposerControlledState,
isComposerNativeEcho,
pruneAcknowledgedComposerNativeEvents,
resolveComposerControlledEventCount,
@@ -42,6 +43,19 @@ describe("isComposerNativeEcho", () => {
it("matches value and revision when selection is uncontrolled", () => {
expect(isComposerNativeEcho("native", null, 3, snapshots)).toBe(true);
});
it("does not claim a controlled selection against an assumed state without one", () => {
// An echo payload serializes `selection: null`; classifying a controlled
// selection as an echo of an assumed state would drop a parent caret move.
const assumed = [{ eventCount: 3, value: "native", selection: null }];
expect(isComposerNativeEcho("native", { start: 0, end: 0 }, 3, assumed)).toBe(false);
expect(isComposerNativeEcho("other", { start: 0, end: 0 }, 3, assumed)).toBe(false);
});
it("matches an assumed state when selection is uncontrolled", () => {
const assumed = [{ eventCount: 3, value: "native", selection: null }];
expect(isComposerNativeEcho("native", null, 3, assumed)).toBe(true);
});
});
describe("resolveComposerControlledEventCount", () => {
@@ -95,7 +109,7 @@ describe("pruneAcknowledgedComposerNativeEvents", () => {
selection: { start: eventCount, end: eventCount },
}));
expect(pruneAcknowledgedComposerNativeEvents(snapshots, 999)).toEqual([]);
expect(pruneAcknowledgedComposerNativeEvents(snapshots, 999)).toEqual([snapshots[999]]);
});
it("retains native events that arrive after the acknowledged render", () => {
@@ -104,6 +118,77 @@ describe("pruneAcknowledgedComposerNativeEvents", () => {
{ eventCount: 41, value: "ab", selection: { start: 2, end: 2 } },
];
expect(pruneAcknowledgedComposerNativeEvents(snapshots, 40)).toEqual([snapshots[1]]);
expect(pruneAcknowledgedComposerNativeEvents(snapshots, 40)).toEqual(snapshots);
});
it("retains the newest acknowledged snapshot so settled re-renders stay echoes", () => {
const snapshots = [
{ eventCount: 40, value: "a", selection: { start: 1, end: 1 } },
{ eventCount: 41, value: "ab", selection: { start: 2, end: 2 } },
{ eventCount: 42, value: "abc", selection: { start: 3, end: 3 } },
];
const pruned = pruneAcknowledgedComposerNativeEvents(snapshots, 42);
expect(pruned).toEqual([snapshots[2]]);
expect(isComposerNativeEcho("abc", { start: 3, end: 3 }, 42, pruned)).toBe(true);
});
it("keeps the newest of several snapshots sharing the acknowledged revision", () => {
const snapshots = [
{ eventCount: 41, value: "ab", selection: { start: 2, end: 2 } },
{ eventCount: 41, value: "ab", selection: { start: 1, end: 1 } },
];
expect(pruneAcknowledgedComposerNativeEvents(snapshots, 41)).toEqual([snapshots[1]]);
});
});
describe("assumeComposerControlledState", () => {
it("replaces the acknowledged history with the applied controlled state", () => {
const snapshots = [{ eventCount: 3, value: "typed", selection: { start: 5, end: 5 } }];
expect(assumeComposerControlledState(snapshots, 3, "")).toEqual([
{ eventCount: 3, value: "", selection: null },
]);
});
it("keeps native events that raced past the controlled revision", () => {
const snapshots = [
{ eventCount: 3, value: "typed", selection: { start: 5, end: 5 } },
{ eventCount: 4, value: "typed!", selection: { start: 6, end: 6 } },
];
expect(assumeComposerControlledState(snapshots, 3, "")).toEqual([
{ eventCount: 3, value: "", selection: null },
snapshots[1],
]);
});
it("applies a parent caret move on the assumed value at the assumed revision", () => {
// Same value, new caret: not an echo (so the selection is serialized) but
// still stamped at the assumed revision so the editor accepts it.
const snapshots = assumeComposerControlledState([], 3, "typed");
expect(isComposerNativeEcho("typed", { start: 2, end: 2 }, 3, snapshots)).toBe(false);
expect(resolveComposerControlledEventCount("typed", { start: 2, end: 2 }, 3, snapshots)).toBe(
3,
);
});
it("re-applies a parent value that round-trips back to an acknowledged state", () => {
// Native acknowledged "typed", the parent then controlled the editor to ""
// (a send clearing the draft) and back to "typed" (the send failed and the
// draft was restored). The restore must be a fresh non-echo edit stamped at
// the current revision, not an echo the editor would drop.
const snapshots = assumeComposerControlledState(
[{ eventCount: 3, value: "typed", selection: { start: 5, end: 5 } }],
3,
"",
);
expect(isComposerNativeEcho("typed", { start: 5, end: 5 }, 3, snapshots)).toBe(false);
expect(resolveComposerControlledEventCount("typed", { start: 5, end: 5 }, 3, snapshots)).toBe(
3,
);
});
});
@@ -31,10 +31,7 @@ export function resolveComposerControlledEventCount(
if (snapshot?.value !== value) continue;
newestValueEventCount ??= snapshot.eventCount;
if (
selection === null ||
(snapshot.selection?.start === selection.start && snapshot.selection.end === selection.end)
) {
if (selection === null || snapshotSelectionMatches(snapshot, selection)) {
return snapshot.eventCount;
}
}
@@ -49,6 +46,21 @@ export function resolveComposerControlledEventCount(
return mostRecentEventCount;
}
// A snapshot without a selection describes a state the editor applied itself
// (an assumed controlled document, where the native side may have bounded the
// caret). Revision stamping treats it as matching any controlled selection so
// a parent caret move on the assumed value stays at the assumed revision and
// passes the editor's staleness guard. Echo detection must not reuse this
// wildcard: an echo payload serializes `selection: null`, which would drop
// that caret move instead of applying it.
function snapshotSelectionMatches(
snapshot: ComposerNativeEventSnapshot,
selection: ComposerEditorSelection,
): boolean {
if (snapshot.selection === null) return true;
return snapshot.selection.start === selection.start && snapshot.selection.end === selection.end;
}
export function isComposerNativeEcho(
value: string,
selection: ComposerEditorSelection | null,
@@ -62,7 +74,9 @@ export function isComposerNativeEcho(
snapshot.eventCount === eventCount &&
snapshot.value === value &&
(selection === null ||
(snapshot.selection?.start === selection.start && snapshot.selection.end === selection.end))
(snapshot.selection !== null &&
snapshot.selection.start === selection.start &&
snapshot.selection.end === selection.end))
) {
return true;
}
@@ -70,9 +84,43 @@ export function isComposerNativeEcho(
return false;
}
/**
* Records that a parent-driven controlled document was handed to the native
* editor. From that point the acknowledged snapshot history describes a
* superseded native state, so it is replaced with the assumed applied state;
* a later parent update back to a previously acknowledged value must classify
* as a fresh edit, not as a native echo the editor would drop. Native events
* that raced past the controlled revision stay authoritative and are kept.
*/
export function assumeComposerControlledState(
snapshots: ReadonlyArray<ComposerNativeEventSnapshot>,
eventCount: number,
value: string,
): ComposerNativeEventSnapshot[] {
return [
{ eventCount, value, selection: null },
...snapshots.filter((snapshot) => snapshot.eventCount > eventCount),
];
}
export function pruneAcknowledgedComposerNativeEvents(
snapshots: ReadonlyArray<ComposerNativeEventSnapshot>,
acknowledgedEventCount: number,
): ComposerNativeEventSnapshot[] {
return snapshots.filter((snapshot) => snapshot.eventCount > acknowledgedEventCount);
// The newest acknowledged snapshot must survive pruning: it is what lets a
// later, unrelated re-render classify the settled composer state as a native
// echo instead of a parent-driven edit that would re-control the caret (and
// reset the keyboard's autocorrect context on iOS).
let latestAcknowledgedIndex = -1;
for (let index = snapshots.length - 1; index >= 0; index -= 1) {
const snapshot = snapshots[index];
if (snapshot !== undefined && snapshot.eventCount <= acknowledgedEventCount) {
latestAcknowledgedIndex = index;
break;
}
}
return snapshots.filter(
(snapshot, index) =>
index === latestAcknowledgedIndex || snapshot.eventCount > acknowledgedEventCount,
);
}