Skip to content

armgit / cindy

Public Imported from GitHub
0

Consider it done. The open-source AI agent that works out of the box · 想到,就能做到。开源、开箱即用的 AI Agent。

fix(mobile): 校正第三方键盘停稳后的输入栏位置

Cindy17e92f877e6a
diff --git a/apps/mobile/src/__tests__/composerDockKeyboard.test.tsx b/apps/mobile/src/__tests__/composerDockKeyboard.test.tsx
new file mode 100644
index 0000000000..d4b08b0a25
--- /dev/null
+++ b/apps/mobile/src/__tests__/composerDockKeyboard.test.tsx
@@ -0,0 +1,163 @@
+// @vitest-environment jsdom
+import { act } from "react";
+import { createRoot, type Root } from "react-dom/client";
+import type {
+ KeyboardEvent,
+ KeyboardEventName,
+ KeyboardMetrics,
+} from "react-native";
+import { afterEach, beforeEach, expect, it, vi } from "vitest";
+import { useComposerDockKeyboardHeight } from "@/session/useComposerDockKeyboardHeight";
+
+const native = vi.hoisted(() => ({
+ keyboard: { height: { value: 0 }, state: { value: 0 } },
+ viewport: { width: 390, height: 844 },
+ shown: false,
+ metrics: undefined as KeyboardMetrics | undefined,
+ listeners: new Map<KeyboardEventName, Set<(event: KeyboardEvent) => void>>(),
+}));
+vi.mock("react-native", () => ({
+ useWindowDimensions: () => native.viewport,
+ Keyboard: {
+ metrics: () => native.metrics,
+ isVisible: () => native.shown,
+ addListener: (
+ name: KeyboardEventName,
+ listener: (event: KeyboardEvent) => void,
+ ) => {
+ const listeners = native.listeners.get(name) ?? new Set();
+ native.listeners.set(name, listeners);
+ listeners.add(listener);
+ return { remove: () => listeners.delete(listener) };
+ },
+ },
+}));
+vi.mock("react-native-reanimated", async () => {
+ const { useRef } = await import("react");
+ return {
+ KeyboardState: { UNKNOWN: 0, OPENING: 1, OPEN: 2, CLOSING: 3, CLOSED: 4 },
+ useAnimatedKeyboard: () => native.keyboard,
+ useSharedValue: (value: number) => useRef({ value }).current,
+ useDerivedValue: (read: () => number) => ({
+ get value() {
+ return read();
+ },
+ }),
+ };
+});
+
+let result: { readonly value: number };
+let root: Root;
+let container: HTMLDivElement;
+function Harness() {
+ result = useComposerDockKeyboardHeight();
+ return null;
+}
+function frame(
+ height = 350,
+ screenY = 844 - height,
+ width = 390,
+): KeyboardMetrics {
+ return { height, screenY, width, screenX: 0 };
+}
+function emit(name: KeyboardEventName, endCoordinates = frame()) {
+ act(() => {
+ for (const listener of native.listeners.get(name) ?? []) {
+ listener({ endCoordinates, duration: 0, easing: "keyboard" });
+ }
+ });
+}
+beforeEach(() => {
+ Object.assign(globalThis, { IS_REACT_ACT_ENVIRONMENT: true });
+ native.keyboard.height.value = 0;
+ native.keyboard.state.value = 0;
+ native.shown = false;
+ native.metrics = undefined;
+ native.viewport = { width: 390, height: 844 };
+ native.listeners.clear();
+ container = document.createElement("div");
+ root = createRoot(container);
+});
+afterEach(() => {
+ act(() => root.unmount());
+ container.remove();
+});
+function mount() {
+ act(() => root.render(<Harness />));
+}
+
+it("corrects a third-party keyboard height after show, then follows frame-only growth and shrinkage", () => {
+ mount();
+ native.keyboard.state.value = 1;
+ native.keyboard.height.value = 180;
+ emit("keyboardWillShow");
+ expect(result.value).toBe(180);
+ native.keyboard.state.value = 2;
+ native.keyboard.height.value = 300;
+ emit("keyboardDidShow", frame(350));
+ expect(result.value).toBe(350);
+ emit("keyboardDidChangeFrame", frame(430));
+ expect(result.value).toBe(430);
+ emit("keyboardDidChangeFrame", frame(320));
+ expect(result.value).toBe(320);
+});
+
+it("does not pin interactive dismissal or cancellation to the last settled height", () => {
+ mount();
+ native.keyboard.state.value = 2;
+ emit("keyboardDidShow");
+ native.keyboard.state.value = 3;
+ native.keyboard.height.value = 120;
+ expect(result.value).toBe(120);
+ native.keyboard.state.value = 1;
+ native.keyboard.height.value = 220;
+ expect(result.value).toBe(220);
+ native.keyboard.state.value = 2;
+ emit("keyboardDidShow");
+ expect(result.value).toBe(350);
+ emit("keyboardWillHide");
+ native.keyboard.state.value = 3;
+ native.keyboard.height.value = 40;
+ expect(result.value).toBe(40);
+ native.keyboard.state.value = 4;
+ emit("keyboardDidHide");
+ expect(result.value).toBe(0);
+ native.keyboard.state.value = 1;
+ native.keyboard.height.value = 60;
+ emit("keyboardWillShow");
+ expect(result.value).toBe(60);
+});
+
+it("reconciles a keyboard already open when navigating and recomputes after rotation", () => {
+ native.shown = true;
+ native.metrics = frame();
+ mount();
+ expect(result.value).toBe(350);
+ native.viewport = { width: 844, height: 390 };
+ native.metrics = frame(200, 190, 844);
+ act(() => root.render(<Harness />));
+ expect(result.value).toBe(200);
+});
+
+it("does not lift the page for floating, hidden, or cross-fade frames", () => {
+ mount();
+ native.keyboard.state.value = 2;
+ native.keyboard.height.value = 300;
+ for (const metrics of [
+ frame(300, 544, 250),
+ frame(300, 300),
+ frame(300, 844),
+ frame(844, 0),
+ ]) {
+ emit("keyboardDidChangeFrame", metrics);
+ expect(result.value).toBe(0);
+ }
+});
+
+it("removes all subscriptions on unmount", () => {
+ mount();
+ act(() => root.render(null));
+ expect(
+ [...native.listeners.values()].every((listeners) => listeners.size === 0),
+ ).toBe(true);
+});
diff --git a/apps/mobile/src/session/ComposerDockKeyboardFollow.tsx b/apps/mobile/src/session/ComposerDockKeyboardFollow.tsx
index 59a3653d42..de40ba397a 100644
--- a/apps/mobile/src/session/ComposerDockKeyboardFollow.tsx
+++ b/apps/mobile/src/session/ComposerDockKeyboardFollow.tsx
@@ -1,6 +1,7 @@
-import type { ComponentProps, ReactNode } from 'react';
-import { Platform, View } from 'react-native';
-import Reanimated, { useAnimatedKeyboard, useAnimatedStyle } from 'react-native-reanimated';
+import type { ComponentProps, ReactNode } from "react";
+import { Platform, View } from "react-native";
+import Reanimated, { useAnimatedStyle } from "react-native-reanimated";
+import { useComposerDockKeyboardHeight } from "@/session/useComposerDockKeyboardHeight";
/**
* iOS composer dock: the composer (and, in an existing task / partner chat, the
@@ -12,34 +13,87 @@ import Reanimated, { useAnimatedKeyboard, useAnimatedStyle } from 'react-native-
* hooks never change between renders and toggling `active` never remounts the
* composer.
*/
-const TRACKS = Platform.OS === 'ios';
+const TRACKS = Platform.OS === "ios";
/**
* Composer bottom edge: it stays at the new-task button's edge until the keyboard
* reaches it, then rides the keyboard with a fixed gap.
*/
-function dockBottom(keyboardHeight: number, restingBottom: number, keyboardGap: number): number {
- 'worklet';
+function dockBottom(
+ keyboardHeight: number,
+ restingBottom: number,
+ keyboardGap: number,
+): number {
+ "worklet";
return Math.max(restingBottom, keyboardHeight + keyboardGap);
}
type ViewProps = ComponentProps<typeof View>;
/** Lifts its subtree by transform (no per-frame layout for the composer). */
-export function DockKeyboardLift({ active, restingBottom, keyboardGap, style, children, ...props }: ViewProps & {
- active: boolean; restingBottom: number; keyboardGap: number; children?: ReactNode;
+export function DockKeyboardLift({
+ active,
+ restingBottom,
+ keyboardGap,
+ style,
+ children,
+ ...props
+}: ViewProps & {
+ active: boolean;
+ restingBottom: number;
+ keyboardGap: number;
+ children?: ReactNode;
}) {
- if (!TRACKS) return <View {...props} style={style}>{children}</View>;
- return <TrackingLift {...props} active={active} restingBottom={restingBottom} keyboardGap={keyboardGap} style={style}>{children}</TrackingLift>;
+ if (!TRACKS)
+ return (
+ <View {...props} style={style}>
+ {children}
+ </View>
+ );
+ return (
+ <TrackingLift
+ {...props}
+ active={active}
+ restingBottom={restingBottom}
+ keyboardGap={keyboardGap}
+ style={style}
+ >
+ {children}
+ </TrackingLift>
+ );
}
-function TrackingLift({ active, restingBottom, keyboardGap, style, children, ...props }: ViewProps & {
- active: boolean; restingBottom: number; keyboardGap: number; children?: ReactNode;
+function TrackingLift({
+ active,
+ restingBottom,
+ keyboardGap,
+ style,
+ children,
+ ...props
+}: ViewProps & {
+ active: boolean;
+ restingBottom: number;
+ keyboardGap: number;
+ children?: ReactNode;
}) {
- const keyboard = useAnimatedKeyboard();
- const lift = useAnimatedStyle(() => ({
- transform: [{ translateY: active ? restingBottom - dockBottom(keyboard.height.value, restingBottom, keyboardGap) : 0 }],
- }), [active, keyboardGap, restingBottom]);
- return <Reanimated.View {...props} style={[style, lift]}>{children}</Reanimated.View>;
+ const keyboardHeight = useComposerDockKeyboardHeight();
+ const lift = useAnimatedStyle(
+ () => ({
+ transform: [
+ {
+ translateY: active
+ ? restingBottom -
+ dockBottom(keyboardHeight.value, restingBottom, keyboardGap)
+ : 0,
+ },
+ ],
+ }),
+ [active, keyboardGap, restingBottom],
+ );
+ return (
+ <Reanimated.View {...props} style={[style, lift]}>
+ {children}
+ </Reanimated.View>
+ );
}
/** Shrinks the message viewport with the keyboard, in step with the lift above. */
@@ -47,14 +101,28 @@ export function DockKeyboardViewportSpacer({ active }: { active: boolean }) {
return TRACKS ? <TrackingSpacer active={active} /> : null;
}
function TrackingSpacer({ active }: { active: boolean }) {
- const keyboard = useAnimatedKeyboard();
- const style = useAnimatedStyle(() => ({ height: active ? keyboard.height.value : 0 }), [active]);
+ const keyboardHeight = useComposerDockKeyboardHeight();
+ const style = useAnimatedStyle(
+ () => ({ height: active ? keyboardHeight.value : 0 }),
+ [active],
+ );
return <Reanimated.View pointerEvents="none" style={style} />;
}
/** New task: the space under the composer, sized by layout so the page content above shrinks with it. */
-export function DockKeyboardBottomSpacer({ restingBottom, keyboardGap }: { restingBottom: number; keyboardGap: number }) {
- const keyboard = useAnimatedKeyboard();
- const style = useAnimatedStyle(() => ({ height: dockBottom(keyboard.height.value, restingBottom, keyboardGap) }), [keyboardGap, restingBottom]);
+export function DockKeyboardBottomSpacer({
+ restingBottom,
+ keyboardGap,
+}: {
+ restingBottom: number;
+ keyboardGap: number;
+}) {
+ const keyboardHeight = useComposerDockKeyboardHeight();
+ const style = useAnimatedStyle(
+ () => ({
+ height: dockBottom(keyboardHeight.value, restingBottom, keyboardGap),
+ }),
+ [keyboardGap, restingBottom],
+ );
return <Reanimated.View pointerEvents="none" style={style} />;
}
diff --git a/apps/mobile/src/session/useComposerDockKeyboardHeight.ts b/apps/mobile/src/session/useComposerDockKeyboardHeight.ts
new file mode 100644
index 0000000000..29c5b93a41
--- /dev/null
+++ b/apps/mobile/src/session/useComposerDockKeyboardHeight.ts
@@ -0,0 +1,69 @@
+import { useLayoutEffect } from "react";
+import {
+ Keyboard,
+ useWindowDimensions,
+ type KeyboardEvent,
+ type KeyboardMetrics,
+} from "react-native";
+import {
+ KeyboardState,
+ useAnimatedKeyboard,
+ useDerivedValue,
+ useSharedValue,
+} from "react-native-reanimated";
+import { isDockedKeyboard } from "@/auth/loginKeyboardAvoidance";
+
+/** Keep UI-thread motion, but use the public keyboard frame once it settles.
+ * Reanimated 4.5's iOS observer only subscribes to show/hide and can retain an
+ * old height when a third-party keyboard resizes without hiding. Its private
+ * keyboard-view measurement can also differ from the notification's full frame.
+ */
+export function useComposerDockKeyboardHeight() {
+ const keyboard = useAnimatedKeyboard();
+ const viewport = useWindowDimensions();
+ const settledHeight = useSharedValue(-1);
+
+ useLayoutEffect(() => {
+ const overlap = (frame: KeyboardMetrics | undefined) => {
+ if (!frame || frame.screenY === 0) return 0;
+ return isDockedKeyboard(
+ { x: frame.screenX, y: frame.screenY, ...frame },
+ viewport.width,
+ ) && frame.screenY + frame.height >= viewport.height
+ ? Math.max(0, Math.min(frame.height, viewport.height - frame.screenY))
+ : 0;
+ };
+ settledHeight.value = Keyboard.isVisible()
+ ? overlap(Keyboard.metrics())
+ : -1;
+ const settle = (event: KeyboardEvent) => {
+ settledHeight.value = overlap(event.endCoordinates);
+ };
+ const invalidate = () => {
+ settledHeight.value = -1;
+ };
+ const subscriptions = [
+ Keyboard.addListener("keyboardWillShow", invalidate),
+ Keyboard.addListener("keyboardWillHide", invalidate),
+ Keyboard.addListener("keyboardDidShow", settle),
+ Keyboard.addListener("keyboardDidChangeFrame", settle),
+ Keyboard.addListener("keyboardDidHide", () => {
+ settledHeight.value = 0;
+ }),
+ ];
+ return () => {
+ for (const subscription of subscriptions) subscription.remove();
+ };
+ }, [settledHeight, viewport.width, viewport.height]);
+
+ return useDerivedValue(() => {
+ // Interactive dismissal/cancellation must keep following the native frames;
+ // a settled height is not a minimum, or it would pin the composer in place.
+ const moving =
+ keyboard.state.value === KeyboardState.OPENING ||
+ keyboard.state.value === KeyboardState.CLOSING;
+ return !moving && settledHeight.value >= 0
+ ? settledHeight.value
+ : keyboard.height.value;
+ });
+}