Skip to content
TypeScript

fix(mobile): keyboard state follows Android's nonanimated IME show (#25847)

Julius Marminged6f7554c2a49
diff --git a/apps/mobile/src/features/keyboard/keyboardControllerState.test.tsx b/apps/mobile/src/features/keyboard/keyboardControllerState.test.tsx
new file mode 100644
index 00000000000..f628e495f9e
--- /dev/null
+++ b/apps/mobile/src/features/keyboard/keyboardControllerState.test.tsx
@@ -0,0 +1,84 @@
+import { act } from "react";
+import { createRoot } from "react-dom/client";
+import type { KeyboardEventData } from "react-native-keyboard-controller";
+import { expect, it, vi } from "vite-plus/test";
+
+const listeners = vi.hoisted(() => new Map<string, Set<(event: KeyboardEventData) => void>>());
+
+// Exercises the patched library source with only its native bindings replaced.
+vi.mock("react-native-keyboard-controller/src/bindings", () => ({
+ KeyboardEvents: {
+ addListener: (name: string, listener: (event: KeyboardEventData) => void) => {
+ const named = listeners.get(name) ?? new Set();
+ named.add(listener);
+ listeners.set(name, named);
+ return { remove: () => named.delete(listener) };
+ },
+ },
+ KeyboardControllerNative: { dismiss: () => {} },
+}));
+
+import { useKeyboardState } from "react-native-keyboard-controller/src/hooks/useKeyboardState";
+import { KeyboardController } from "react-native-keyboard-controller/src/module";
+
+function emit(name: string, height: number) {
+ const event: KeyboardEventData = {
+ height,
+ duration: 0,
+ timestamp: 1,
+ target: 42,
+ type: "default",
+ appearance: "light",
+ };
+ act(() => {
+ for (const listener of listeners.get(name) ?? []) listener(event);
+ });
+}
+
+function KeyboardState() {
+ const { isVisible, height } = useKeyboardState();
+ return <output>{JSON.stringify({ isVisible, height })}</output>;
+}
+
+// The library keeps keyboard state at module scope; every test starts and ends hidden.
+function setup() {
+ emit("keyboardDidHide", 0);
+ return { [Symbol.dispose]: () => emit("keyboardDidHide", 0) };
+}
+
+function renderKeyboardState() {
+ const container = document.createElement("div");
+ const root = createRoot(container);
+ act(() => root.render(<KeyboardState />));
+ return { container, [Symbol.dispose]: () => act(() => root.unmount()) };
+}
+
+// Android's syncKeyboardPosition repairs a nonanimated IME inset change with
+// keyboardDidHide then keyboardDidShow, and no keyboardWillShow.
+it("reports the keyboard shown after Android repairs the IME inset without keyboardWillShow", () => {
+ using _keyboard = setup();
+ using screen = renderKeyboardState();
+
+ emit("keyboardDidShow", 376);
+
+ expect({
+ isVisible: KeyboardController.isVisible(),
+ height: KeyboardController.state().height,
+ hook: JSON.parse(screen.container.textContent ?? ""),
+ }).toEqual({ isVisible: true, height: 376, hook: { isVisible: true, height: 376 } });
+});
+
+it("waits for the native hide before dismiss resolves after a didShow-only repair", async () => {
+ using _keyboard = setup();
+ emit("keyboardDidShow", 376);
+
+ let dismissed = false;
+ const dismissal = KeyboardController.dismiss().then(() => {
+ dismissed = true;
+ });
+ await act(async () => {});
+
+ expect(dismissed).toBe(false);
+ emit("keyboardDidHide", 0);
+ await dismissal;
+});
diff --git a/apps/mobile/src/features/terminal/ThreadTerminalRouteScreen.tsx b/apps/mobile/src/features/terminal/ThreadTerminalRouteScreen.tsx
index 74ae491786d..9b3db1e3525 100644
--- a/apps/mobile/src/features/terminal/ThreadTerminalRouteScreen.tsx
+++ b/apps/mobile/src/features/terminal/ThreadTerminalRouteScreen.tsx
@@ -14,7 +14,7 @@ import { useNativeColumnLayoutMetrics } from "../../native/native-layout-metrics
import { useContentTopInset } from "../../components/ui/useBarInset";
import { StackActions, useNavigation, type StaticScreenProps } from "@react-navigation/native";
import { useAtomMount } from "@effect/atom-react";
-import { useMemo, useRef, useState } from "react";
+import { useMemo, useRef, useState, useSyncExternalStore } from "react";
import { Platform, Pressable, View } from "react-native";
import { useSafeAreaInsets } from "react-native-safe-area-context";
import { AppText as Text } from "../../components/ui/AppText";
@@ -35,7 +35,6 @@ import {
ComposerToolbarScroller,
} from "../../components/ComposerToolbar";
import { EmptyState } from "../../components/ui/EmptyState";
-import { useSoftKeyboardShowing } from "../keyboard/useSoftKeyboardShowing";
import { GlassSurface } from "../../components/ui/GlassSurface";
import { LoadingScreen } from "../../components/LoadingScreen";
import { ScreenContent } from "../../components/ui/ScreenContent";
@@ -90,6 +89,7 @@ import {
} from "./terminalInput";
import { createTerminalPasteSession } from "./terminalPaste";
import { cacheTerminalGridSize, getCachedTerminalGridSize } from "./terminalUiState";
+import { getKeyboardShowEpoch, subscribeKeyboardShowing } from "./terminalKeyboardShowing";
function TerminalHeader(props: {
readonly subtitle: string;
@@ -567,29 +567,25 @@ function ThreadTerminal(props: {
{ kind: "send", key: "dash", label: "-", data: "-" },
];
}, [hostPlatform]);
- const keyboardState = useKeyboardState((state) => ({
- height: state.height,
- isVisible: state.isVisible,
- }));
- // The accessory leaves as soon as the keyboard starts hiding.
- const keyboardShowing = useSoftKeyboardShowing();
+ const isKeyboardVisible = useKeyboardState((state) => state.isVisible);
+ const keyboardHeight = useKeyboardState((state) => state.height);
+ const keyboardShowEpoch = useSyncExternalStore(subscribeKeyboardShowing, getKeyboardShowEpoch);
// The accessory follows the keyboard, except that the dismiss and show
// buttons flip it ahead of the keyboard animation.
- const [accessory, setAccessory] = useState({ keyboardShowing, dismissed: false });
- if (accessory.keyboardShowing !== keyboardShowing) {
- setAccessory({ keyboardShowing, dismissed: !keyboardShowing });
+ const [accessory, setAccessory] = useState({ keyboardShowEpoch, dismissed: false });
+ if (accessory.keyboardShowEpoch !== keyboardShowEpoch) {
+ setAccessory({ keyboardShowEpoch, dismissed: keyboardShowEpoch === 0 });
}
const isAccessoryDismissed = accessory.dismissed;
- const isAccessoryVisible = canOperateTerminal && keyboardState.isVisible && !isAccessoryDismissed;
+ const isAccessoryVisible = canOperateTerminal && isKeyboardVisible && !isAccessoryDismissed;
// Android's terminal owns an EditText; turning off autoFocus also clears its native focus.
const terminalAutoFocus =
Platform.OS === "android"
? !isAccessoryDismissed &&
- (!SHOWCASE_ENABLED || keyboardFocusRequest > 0 || keyboardState.isVisible)
+ (!SHOWCASE_ENABLED || keyboardFocusRequest > 0 || isKeyboardVisible)
: !SHOWCASE_ENABLED;
const terminalBottomInset =
- (keyboardState.isVisible ? keyboardState.height : 0) +
- (isAccessoryVisible ? TERMINAL_ACCESSORY_HEIGHT : 0);
+ (isKeyboardVisible ? keyboardHeight : 0) + (isAccessoryVisible ? TERMINAL_ACCESSORY_HEIGHT : 0);
const terminalMenuSessions: ReadonlyArray<TerminalMenuSession> = buildTerminalMenuSessions({
knownSessions: knownSessions ?? [],
@@ -845,8 +841,7 @@ function ThreadTerminal(props: {
: terminalTheme.background,
// Measured top reservation is zero when UIKit already inset the body or moved the bar.
paddingTop: contentTopInset,
- paddingBottom:
- Platform.OS === "android" && !keyboardState.isVisible ? insets.bottom : 0,
+ paddingBottom: Platform.OS === "android" && !isKeyboardVisible ? insets.bottom : 0,
}}
>
{!isEnvironmentReady ? (
@@ -941,7 +936,7 @@ function ThreadTerminal(props: {
/>
</View>
- {Platform.OS === "android" && !keyboardState.isVisible ? (
+ {Platform.OS === "android" && !isKeyboardVisible ? (
<View className="min-h-14 flex-row items-center gap-2 bg-card-alt px-2">
{hasNativeTerminalSurface() ? (
<Button label="Attach output" tone="text" onPress={requestCapture} />
@@ -965,7 +960,7 @@ function ThreadTerminal(props: {
style={{
paddingBottom:
8 +
- (keyboardState.isVisible
+ (isKeyboardVisible
? 0
: (nativeColumnMetrics?.safeArea.bottom ?? insets.bottom)),
}}
@@ -1023,7 +1018,7 @@ function ThreadTerminal(props: {
</ComposerToolbarRow>
</View>
</KeyboardStickyView>
- ) : canOperateTerminal && !keyboardState.isVisible && Platform.OS !== "android" ? (
+ ) : canOperateTerminal && !isKeyboardVisible && Platform.OS !== "android" ? (
<Pressable
accessibilityLabel="Show keyboard"
accessibilityRole="button"
diff --git a/apps/mobile/src/features/terminal/terminalKeyboardShowing.test.ts b/apps/mobile/src/features/terminal/terminalKeyboardShowing.test.ts
new file mode 100644
index 00000000000..2d5272d3510
--- /dev/null
+++ b/apps/mobile/src/features/terminal/terminalKeyboardShowing.test.ts
@@ -0,0 +1,66 @@
+import { expect, it, vi } from "vite-plus/test";
+
+const listeners = vi.hoisted(() => new Map<string, Set<() => void>>());
+
+vi.mock("react-native-keyboard-controller", () => ({
+ KeyboardController: { isVisible: () => false },
+ KeyboardEvents: {
+ addListener: (name: string, listener: () => void) => {
+ const named = listeners.get(name) ?? new Set();
+ named.add(listener);
+ listeners.set(name, named);
+ return { remove: () => named.delete(listener) };
+ },
+ },
+}));
+
+import { getKeyboardShowEpoch, subscribeKeyboardShowing } from "./terminalKeyboardShowing";
+
+function emit(name: string) {
+ for (const listener of listeners.get(name) ?? []) listener();
+}
+
+// Android's syncKeyboardPosition repairs a nonanimated IME inset change with
+// keyboardDidHide then keyboardDidShow, and no will-events.
+it("keeps the accessory through Android's did-only repair and starts a new show after it", () => {
+ // Two mounted terminal screens, each reading the snapshot when notified.
+ const seen = [0, 0];
+ const unsubscribes = seen.map((_, index) => {
+ seen[index] = getKeyboardShowEpoch();
+ return subscribeKeyboardShowing(() => {
+ seen[index] = getKeyboardShowEpoch();
+ });
+ });
+ const trace = [
+ "keyboardWillShow",
+ "keyboardDidShow",
+ "keyboardDidHide",
+ "keyboardDidShow",
+ "keyboardWillHide",
+ "keyboardWillShow",
+ ].map((name) => {
+ emit(name);
+ return {
+ epoch: getKeyboardShowEpoch(),
+ inSync: seen.every((s) => s === getKeyboardShowEpoch()),
+ };
+ });
+
+ const [shown, settled, repairHidden, repairShown, hidden, reshown] = trace.map((t) => t.epoch);
+ expect({
+ neverHiddenByRepair: [shown, settled, repairHidden, repairShown].every((epoch) => epoch !== 0),
+ sameShow: settled === shown && repairHidden === shown,
+ newShow: repairShown !== shown,
+ hidden,
+ newShowAfterHide: reshown !== 0 && reshown !== repairShown,
+ subscribersInSync: trace.every((t) => t.inSync),
+ }).toEqual({
+ neverHiddenByRepair: true,
+ sameShow: true,
+ newShow: true,
+ hidden: 0,
+ newShowAfterHide: true,
+ subscribersInSync: true,
+ });
+ for (const unsubscribe of unsubscribes) unsubscribe();
+});
diff --git a/apps/mobile/src/features/terminal/terminalKeyboardShowing.ts b/apps/mobile/src/features/terminal/terminalKeyboardShowing.ts
new file mode 100644
index 00000000000..7f3c745c6f1
--- /dev/null
+++ b/apps/mobile/src/features/terminal/terminalKeyboardShowing.ts
@@ -0,0 +1,40 @@
+import { KeyboardController, KeyboardEvents } from "react-native-keyboard-controller";
+
+// The accessory leaves on willHide, before `useKeyboardState` sees didHide. Android
+// repairs a nonanimated IME change with didHide then didShow alone: that didHide must
+// not hide the accessory (it would clear the terminal's focus), but the didShow after
+// it starts a new show so a dismissed accessory comes back.
+const subscribers = new Set<() => void>();
+let showEpoch = 1;
+let keyboardShowing = KeyboardController.isVisible();
+let hiddenSinceShow = !keyboardShowing;
+
+const notify = () => {
+ for (const subscriber of subscribers) subscriber();
+};
+const show = () => {
+ if (hiddenSinceShow) showEpoch += 1;
+ hiddenSinceShow = false;
+ keyboardShowing = true;
+ notify();
+};
+KeyboardEvents.addListener("keyboardWillShow", show);
+KeyboardEvents.addListener("keyboardDidShow", show);
+KeyboardEvents.addListener("keyboardWillHide", () => {
+ keyboardShowing = false;
+ hiddenSinceShow = true;
+ notify();
+});
+KeyboardEvents.addListener("keyboardDidHide", () => {
+ hiddenSinceShow = true;
+});
+
+export function subscribeKeyboardShowing(onChange: () => void) {
+ subscribers.add(onChange);
+ return () => {
+ subscribers.delete(onChange);
+ };
+}
+
+// 0 while hidden; otherwise a number that changes with every new show.
+export const getKeyboardShowEpoch = () => (keyboardShowing ? showEpoch : 0);
diff --git a/apps/mobile/vite.config.ts b/apps/mobile/vite.config.ts
index 629eef984d8..5aab6e4a1cd 100644
--- a/apps/mobile/vite.config.ts
+++ b/apps/mobile/vite.config.ts
@@ -43,6 +43,7 @@ const reactTests = [
"src/features/layout/workspace/useSearchScrollRestoration.test.tsx",
"src/features/connection/ConnectionsNewRouteScreen.test.tsx",
"src/features/devices/device-stream.browser.test.ts",
+ "src/features/keyboard/keyboardControllerState.test.tsx",
];
const sourceRoot = `${normalizePath(NodeURL.fileURLToPath(new URL("./src", import.meta.url)))}/`;
diff --git a/patches/[email protected] b/patches/[email protected]
index 4c13280a6ed..66cd20076e6 100644
--- a/patches/[email protected]
+++ b/patches/[email protected]
@@ -320,6 +320,36 @@ index 11e81a9..de39eac 100644
}
//# sourceMappingURL=index.js.map
\ No newline at end of file
+diff --git a/lib/commonjs/hooks/useKeyboardState/index.js b/lib/commonjs/hooks/useKeyboardState/index.js
+index a4b287006a47011a58c8a16f19b31a479087f44e..4084025d644c8555b269f9d496266e2cb3234024 100644
+--- a/lib/commonjs/hooks/useKeyboardState/index.js
++++ b/lib/commonjs/hooks/useKeyboardState/index.js
+@@ -7,7 +7,7 @@ exports.useKeyboardState = useKeyboardState;
+ var _react = require("react");
+ var _bindings = require("../../bindings");
+ var _module = require("../../module");
+-const EVENTS = ["keyboardWillShow", "keyboardDidHide"];
++const EVENTS = ["keyboardWillShow", "keyboardDidShow", "keyboardDidHide"];
+ const getLatestState = () => ({
+ ..._module.KeyboardController.state(),
+ isVisible: _module.KeyboardController.isVisible()
+diff --git a/lib/commonjs/module.js b/lib/commonjs/module.js
+index f27c5a095129cf60831088a73ce94d44f3ba52cd..3c2f7569510d0a56fd937b6e91a6adc0d5ff6f59 100644
+--- a/lib/commonjs/module.js
++++ b/lib/commonjs/module.js
+@@ -22,6 +22,12 @@ _bindings.KeyboardEvents.addListener("keyboardWillShow", e => {
+ isClosed = false;
+ lastState = e;
+ });
++// Android re-syncs an IME inset that changes without an animation with keyboardDidShow
++// alone. Drop with kirillzyusko/react-native-keyboard-controller#1698.
++_bindings.KeyboardEvents.addListener("keyboardDidShow", e => {
++ isClosed = false;
++ lastState = e;
++});
+ const dismiss = async options => {
+ const keepFocus = (options === null || options === void 0 ? void 0 : options.keepFocus) ?? false;
+ const animated = (options === null || options === void 0 ? void 0 : options.animated) ?? true;
diff --git a/lib/module/components/KeyboardChatScrollView/index.js b/lib/module/components/KeyboardChatScrollView/index.js
index e0c8391..8df802a 100644
--- a/lib/module/components/KeyboardChatScrollView/index.js
@@ -568,6 +598,36 @@ index cdca47b..3ea3a7f 100644
export { useExtraContentPadding };
//# sourceMappingURL=index.js.map
\ No newline at end of file
+diff --git a/lib/module/hooks/useKeyboardState/index.js b/lib/module/hooks/useKeyboardState/index.js
+index 8da7c09fbb398253420d7bfcd9a85abdb981065b..31b1ff4370d8328a0569e559e3bbfa4b201f5a9d 100644
+--- a/lib/module/hooks/useKeyboardState/index.js
++++ b/lib/module/hooks/useKeyboardState/index.js
+@@ -1,7 +1,7 @@
+ import { useEffect, useState } from "react";
+ import { KeyboardEvents } from "../../bindings";
+ import { KeyboardController } from "../../module";
+-const EVENTS = ["keyboardWillShow", "keyboardDidHide"];
++const EVENTS = ["keyboardWillShow", "keyboardDidShow", "keyboardDidHide"];
+ const getLatestState = () => ({
+ ...KeyboardController.state(),
+ isVisible: KeyboardController.isVisible()
+diff --git a/lib/module/module.js b/lib/module/module.js
+index 01aad2effee498a8daec55e1d4644a5fbc723765..1140b706265d6c4295581c96b82b27bbf9e6d020 100644
+--- a/lib/module/module.js
++++ b/lib/module/module.js
+@@ -16,6 +16,12 @@ KeyboardEvents.addListener("keyboardWillShow", e => {
+ isClosed = false;
+ lastState = e;
+ });
++// Android re-syncs an IME inset that changes without an animation with keyboardDidShow
++// alone. Drop with kirillzyusko/react-native-keyboard-controller#1698.
++KeyboardEvents.addListener("keyboardDidShow", e => {
++ isClosed = false;
++ lastState = e;
++});
+ const dismiss = async options => {
+ const keepFocus = (options === null || options === void 0 ? void 0 : options.keepFocus) ?? false;
+ const animated = (options === null || options === void 0 ? void 0 : options.animated) ?? true;
diff --git a/lib/typescript/components/KeyboardChatScrollView/types.d.ts b/lib/typescript/components/KeyboardChatScrollView/types.d.ts
index eba1514..6597d80 100644
--- a/lib/typescript/components/KeyboardChatScrollView/types.d.ts
@@ -995,3 +1055,34 @@ index 99cc6c6..d883e76 100644
);
}
+diff --git a/src/hooks/useKeyboardState/index.ts b/src/hooks/useKeyboardState/index.ts
+index e5fe38dd8e7b8370bfb575296259933094857ca5..d0b98f60a6d7ad7f72ebd70b22e1ce6b7fb56874 100644
+--- a/src/hooks/useKeyboardState/index.ts
++++ b/src/hooks/useKeyboardState/index.ts
+@@ -5,7 +5,7 @@ import { KeyboardController } from "../../module";
+
+ import type { IKeyboardState } from "../../types";
+
+-const EVENTS = ["keyboardWillShow", "keyboardDidHide"] as const;
++const EVENTS = ["keyboardWillShow", "keyboardDidShow", "keyboardDidHide"] as const;
+
+ const getLatestState = () => ({
+ ...KeyboardController.state(),
+diff --git a/src/module.ts b/src/module.ts
+index f74941914c9ecebbd0a6c2ba55c5436378de79d4..b7223cff162d18be11f8de248a7bb8f32e694658 100644
+--- a/src/module.ts
++++ b/src/module.ts
+@@ -26,6 +26,13 @@ KeyboardEvents.addListener("keyboardWillShow", (e) => {
+ lastState = e;
+ });
+
++// Android re-syncs an IME inset that changes without an animation with keyboardDidShow
++// alone. Drop with kirillzyusko/react-native-keyboard-controller#1698.
++KeyboardEvents.addListener("keyboardDidShow", (e) => {
++ isClosed = false;
++ lastState = e;
++});
++
+ const dismiss = async (options?: Partial<DismissOptions>): Promise<void> => {
+ const keepFocus = options?.keepFocus ?? false;
+ const animated = options?.animated ?? true;
diff --git a/pnpm-lock.yaml b/pnpm-lock.yaml
index b413300db9d..3e1dd4d26a4 100644
--- a/pnpm-lock.yaml
+++ b/pnpm-lock.yaml
@@ -384,7 +384,7 @@ patchedDependencies:
[email protected]: f1e680afec85f650699ea756f91f469844ec4c976f4f168492a45c6b3f67d651
[email protected]: abe20e1d1c23549297cbbc818e14fe479b41455930d9663135d6b40fe359b626
[email protected]: 4aa038d541c7ddcc8f1437eb3e7b4f769f61de78e7f91b53f9805dfca608474d
- [email protected]: 3fa3d03e203a23165a439c4cddf5372ccd53acf337389793211be64dcdafccef
+ [email protected]: 4e9b5a52aa8c1f9de8082bad281ee979df7860fc77ec49820d4ed00c3c7cc5a2
[email protected]: 6f52854210f61bef499850ebd498229a111bc34ec5b2a4925e644f2f48f42760
[email protected]: 95ee26e5fcab5f50bc4b4c47b3f7e6278a0b20850205efb9f6ee7e70a22d2b59
[email protected]: 81caa279ec3dc1f81209062133b66e8f824e13f106cca57f1fa732a72c2ab378
@@ -745,7 +745,7 @@ importers:
react-native-keyboard-controller:
specifier: 1.22.8
- version: 1.22.8(patch_hash=3fa3d03e203a23165a439c4cddf5372ccd53acf337389793211be64dcdafccef)(e2a826d844fe10cdcbda558127861778)
+ version: 1.22.8(patch_hash=4e9b5a52aa8c1f9de8082bad281ee979df7860fc77ec49820d4ed00c3c7cc5a2)(e2a826d844fe10cdcbda558127861778)
react-native-nitro-modules:
specifier: 0.37.1
@@ -21272,7 +21272,7 @@ snapshots:
react: 19.3.0
- [email protected](patch_hash=3fa3d03e203a23165a439c4cddf5372ccd53acf337389793211be64dcdafccef)(e2a826d844fe10cdcbda558127861778):
+ [email protected](patch_hash=4e9b5a52aa8c1f9de8082bad281ee979df7860fc77ec49820d4ed00c3c7cc5a2)(e2a826d844fe10cdcbda558127861778):
dependencies:
react: 19.3.0