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): 同步键盘避让与输入卡片动画 (#3945)

Dashbf911de55d3d
diff --git a/apps/mobile/app/sessions/[sessionId].tsx b/apps/mobile/app/sessions/[sessionId].tsx
index 46610f2deb..2cec659e5c 100644
--- a/apps/mobile/app/sessions/[sessionId].tsx
+++ b/apps/mobile/app/sessions/[sessionId].tsx
@@ -45,7 +45,6 @@ import {
AppState,
BackHandler,
Keyboard,
- KeyboardAvoidingView,
Linking,
Platform,
Pressable,
@@ -349,6 +348,7 @@ import {
} from '@/session/MobileComposerInputRow';
import { VoiceRecordingPillContent, useMobileVoiceRecordingTimer } from '@/session/VoiceRecordingPill';
import { useComposerCardTransition } from '@/session/useComposerCardTransition';
+import { ComposerKeyboardAvoidingView } from '@/session/ComposerKeyboardAvoidingView';
import { useComposerResize } from '@/session/useComposerResize';
import { useMobileKeyboardState } from '@/session/useMobileKeyboardState';
import { buildSessionComposerLayout } from '@/session/sessionComposerLayout';
@@ -2709,7 +2709,7 @@ export default function SessionScreen() {
|| permissionSheetOpen
|| voiceIsBusy
|| composerVoiceHoldActive;
- useComposerCardTransition(composerCardActive);
+ useComposerCardTransition(composerCardActive, keyboardState);
const composerChromeHeight = useMemo(() => {
const statusReserve = voiceStatusVisible
? COMPOSER_STATUS_ROW_RESERVED_HEIGHT + COMPOSER_STACK_GAP_HEIGHT
@@ -3017,7 +3017,7 @@ export default function SessionScreen() {
return active;
}, [isPointInsideSendButton]);
// Bottom padding the message list needs to clear the composer = the composer's own height only.
- // The keyboard lift is already applied once by the KeyboardAvoidingView (iOS behavior="padding"),
+ // The keyboard lift is already applied once by ComposerKeyboardAvoidingView,
// so ALSO adding keyboardBottomInset here double-counted the keyboard and shoved the conversation
// up (badly visible once the list bottom-anchors its content). Keyboard-closed is unchanged —
// keyboardBottomInset is 0 then, so this matches the previous value.
@@ -9135,7 +9135,8 @@ export default function SessionScreen() {
return (
<View style={styles.safeArea} testID="session.screen">
- <KeyboardAvoidingView
+ <ComposerKeyboardAvoidingView
+ keyboard={keyboardState}
// 抽屉开着时把背后内容从读屏树里摘掉:iOS 用 accessibilityElementsHidden
// (与抽屉侧 accessibilityViewIsModal 配对),Android 用 importantForAccessibility
// ——后者才对 TalkBack 生效(与 ComposerRichInput 的双平台配对惯例一致)。
@@ -10014,7 +10015,7 @@ export default function SessionScreen() {
) : null}
</View>
</View>
- </KeyboardAvoidingView>
+ </ComposerKeyboardAvoidingView>
{shareSelectionActive && selectedShareMessages.length > 0 ? (
<ConversationShareSvg
allShareableIds={allShareableIds}
diff --git a/apps/mobile/app/sessions/new.tsx b/apps/mobile/app/sessions/new.tsx
index a7c9e5fdae..e68ca4dd91 100644
--- a/apps/mobile/app/sessions/new.tsx
+++ b/apps/mobile/app/sessions/new.tsx
@@ -17,7 +17,6 @@ import {
ActivityIndicator,
AppState,
FlatList,
- KeyboardAvoidingView,
Linking,
Platform,
Pressable,
@@ -224,6 +223,7 @@ import {
} from '@/session/MobileComposerInputRow';
import { VoiceRecordingPillContent, useMobileVoiceRecordingTimer } from '@/session/VoiceRecordingPill';
import { useComposerCardTransition } from '@/session/useComposerCardTransition';
+import { ComposerKeyboardAvoidingView } from '@/session/ComposerKeyboardAvoidingView';
import { useComposerResize } from '@/session/useComposerResize';
import { useMobileKeyboardState } from '@/session/useMobileKeyboardState';
import {
@@ -1487,7 +1487,7 @@ export default function NewRemoteSessionScreen() {
|| permissionSheetOpen
|| voiceIsBusy
|| composerVoiceHoldActive;
- useComposerCardTransition(composerCardActive);
+ useComposerCardTransition(composerCardActive, keyboardState);
// 下拉收起 = 退出聚焦激活态(模型浮窗已是独立 Modal,拖拽手势够不到它,无需在此关闭)。
// 语音结束 hold 态未聚焦,blur 是 no-op,需显式解除 hold 才能收回简洁态。
const handleComposerSnapToAuto = useCallback(() => {
@@ -5297,7 +5297,9 @@ export default function NewRemoteSessionScreen() {
return (
<SafeAreaView style={styles.safeArea} testID="newSession.screen">
- <KeyboardAvoidingView
+ <ComposerKeyboardAvoidingView
+ keyboard={keyboardState}
+ bottomInset={safeAreaInsets.bottom}
behavior={keyboardAvoidingBehaviorForPlatform(
Platform.OS === 'ios' ? 'ios' : Platform.OS === 'android' ? 'android' : 'web',
)}
@@ -5825,7 +5827,7 @@ export default function NewRemoteSessionScreen() {
</View>
</View>
</View>
- </KeyboardAvoidingView>
+ </ComposerKeyboardAvoidingView>
<ContextSheet
footer={contextSheetView !== 'goal' && pendingMediaAssets.length > 0 ? (
<ContextSheetFooterButton
diff --git a/apps/mobile/src/__tests__/composerKeyboard.test.tsx b/apps/mobile/src/__tests__/composerKeyboard.test.tsx
new file mode 100644
index 0000000000..2cbd572734
--- /dev/null
+++ b/apps/mobile/src/__tests__/composerKeyboard.test.tsx
@@ -0,0 +1,404 @@
+// @vitest-environment jsdom
+import { act, type ReactNode } from 'react';
+import { createRoot, type Root } from 'react-dom/client';
+import type {
+ KeyboardEvent,
+ KeyboardEventName,
+ KeyboardMetrics,
+} from 'react-native';
+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
+import { ComposerKeyboardAvoidingView } from '@/session/ComposerKeyboardAvoidingView';
+import { useMobileKeyboardState } from '@/session/useMobileKeyboardState';
+import { useComposerCardTransition } from '@/session/useComposerCardTransition';
+import { motionDuration } from '@/theme/tokens';
+
+const native = vi.hoisted(() => ({
+ platform: { OS: 'ios' },
+ viewport: { width: 390, height: 844, scale: 3, fontScale: 1 },
+ shown: false,
+ metrics: undefined as KeyboardMetrics | undefined,
+ reducedMotion: false as boolean | null,
+ listeners: new Map<KeyboardEventName, Set<(event: KeyboardEvent) => void>>(),
+ schedule: vi.fn(),
+ configure: vi.fn(),
+ crossFade: vi.fn<() => Promise<boolean>>(),
+}));
+
+vi.mock('react-native', async () => {
+ const { createElement } = await import('react');
+ type Props = {
+ children?: ReactNode;
+ style?: object | object[];
+ behavior?: string;
+ };
+ const View = ({ children, style }: Props) =>
+ createElement(
+ 'div',
+ {
+ 'data-container': 'view',
+ style: Array.isArray(style) ? Object.assign({}, ...style) : style,
+ },
+ children,
+ );
+ return {
+ View,
+ KeyboardAvoidingView: ({ children, behavior, style }: Props) =>
+ createElement(
+ 'div',
+ {
+ 'data-container': 'kav',
+ 'data-behavior': behavior,
+ style,
+ },
+ children,
+ ),
+ Platform: native.platform,
+ useWindowDimensions: () => native.viewport,
+ Keyboard: {
+ get isVisible() {
+ return native.platform.OS === 'web' ? undefined : () => native.shown;
+ },
+ get metrics() {
+ return native.platform.OS === 'web' ? undefined : () => native.metrics;
+ },
+ 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) };
+ },
+ scheduleLayoutAnimation: native.schedule,
+ },
+ LayoutAnimation: { configureNext: native.configure },
+ AccessibilityInfo: { prefersCrossFadeTransitions: native.crossFade },
+ UIManager: {},
+ };
+});
+vi.mock('@/hooks/useReduceMotion', () => ({
+ getCachedReduceMotionEnabled: () => native.reducedMotion,
+ useReduceMotionEnabled: () => native.reducedMotion,
+}));
+
+function Harness({ active = false, inset = 0 }) {
+ const keyboard = useMobileKeyboardState();
+ useComposerCardTransition(active, keyboard);
+ return (
+ <ComposerKeyboardAvoidingView
+ keyboard={keyboard}
+ bottomInset={inset}
+ behavior="height"
+ >
+ <output data-height={keyboard.height} data-visible={keyboard.visible} />
+ </ComposerKeyboardAvoidingView>
+ );
+}
+
+function keyboardEvent(
+ screenY = 544,
+ height = 300,
+ duration = 360,
+): KeyboardEvent {
+ return {
+ duration,
+ easing: 'keyboard',
+ endCoordinates: { screenX: 0, screenY, width: 390, height },
+ };
+}
+
+let root: Root;
+let container: HTMLDivElement;
+function render(props: Parameters<typeof Harness>[0] = {}) {
+ act(() => root.render(<Harness {...props} />));
+}
+function emit(name: KeyboardEventName, event = keyboardEvent()) {
+ act(() => {
+ // 与 RN KeyboardImpl 一致:原生缓存只由 didShow / didHide 更新。
+ if (name === 'keyboardDidShow') {
+ native.shown = true;
+ native.metrics = event.endCoordinates;
+ } else if (name === 'keyboardDidHide') {
+ native.shown = false;
+ native.metrics = undefined;
+ }
+ for (const listener of native.listeners.get(name) ?? []) listener(event);
+ });
+}
+function height() {
+ return Number(container.querySelector('output')?.getAttribute('data-height'));
+}
+function padding() {
+ return (container.firstElementChild as HTMLElement).style.paddingBottom;
+}
+
+beforeEach(() => {
+ Object.assign(globalThis, { IS_REACT_ACT_ENVIRONMENT: true });
+ native.platform.OS = 'ios';
+ native.viewport = { width: 390, height: 844, scale: 3, fontScale: 1 };
+ native.shown = false;
+ native.metrics = undefined;
+ native.reducedMotion = false;
+ native.listeners.clear();
+ native.schedule.mockReset();
+ native.configure.mockReset();
+ native.crossFade.mockReset().mockResolvedValue(false);
+ container = document.createElement('div');
+ document.body.append(container);
+ root = createRoot(container);
+});
+afterEach(() => {
+ act(() => root.unmount());
+ container.remove();
+ vi.restoreAllMocks();
+});
+
+describe('composer keyboard geometry and motion', () => {
+ it('updates both available height and iOS avoidance when an already-open keyboard changes height', () => {
+ render();
+ emit('keyboardWillShow');
+ expect(height()).toBe(300);
+ expect(padding()).toBe('300px');
+ const emojiKeyboard = keyboardEvent(444, 400, 480);
+ emit('keyboardWillChangeFrame', emojiKeyboard);
+ expect(height()).toBe(400);
+ expect(padding()).toBe('400px');
+ expect(native.schedule).toHaveBeenLastCalledWith(emojiKeyboard);
+ expect(container.querySelector('[data-container="kav"]')).toBeNull();
+ });
+
+ it('uses visible overlap while dragging down, including cancellation and the final few points', () => {
+ render();
+ emit('keyboardWillShow');
+ for (const [top, expected] of [
+ [744, 100],
+ [840, 4],
+ [844, 0],
+ [544, 300],
+ ]) {
+ emit('keyboardWillChangeFrame', keyboardEvent(top, 300, 0));
+ expect(height()).toBe(expected);
+ expect(padding()).toBe(`${expected}px`);
+ }
+ expect(native.schedule).toHaveBeenCalledTimes(1);
+ expect(native.configure).toHaveBeenLastCalledWith({
+ duration: 0,
+ update: { duration: 0, type: 'linear' },
+ });
+ });
+
+ it('removes avoidance on hide and ignores late floating keyboard frames until the next show', () => {
+ render();
+ emit('keyboardWillShow');
+ emit('keyboardWillChangeFrame', keyboardEvent(300, 300));
+ expect(padding()).toBe('0px');
+ emit('keyboardWillHide');
+ emit('keyboardWillChangeFrame');
+ expect(height()).toBe(0);
+ emit('keyboardWillShow');
+ expect(height()).toBe(300);
+ });
+
+ it('does not move the whole page for a narrow floating iPad keyboard', () => {
+ render();
+ const floating = keyboardEvent();
+ floating.endCoordinates.width = 250;
+ emit('keyboardWillShow', floating);
+ expect(height()).toBe(0);
+ });
+
+ it('subtracts the new-page safe area once without affecting the full-window detail page', () => {
+ render({ inset: 34 });
+ emit('keyboardWillShow');
+ expect(height()).toBe(300);
+ expect(padding()).toBe('266px');
+ render({ inset: 0 });
+ expect(padding()).toBe('300px');
+ emit('keyboardWillHide');
+ expect(padding()).toBe('0px');
+ });
+
+ it('uses initial metrics only for mounting with an open keyboard, then follows frame events', () => {
+ native.shown = true;
+ native.metrics = keyboardEvent().endCoordinates;
+ render();
+ expect(height()).toBe(300);
+ emit('keyboardWillChangeFrame', keyboardEvent(644));
+ expect(height()).toBe(200);
+ });
+
+ it('deduplicates equal show/frame geometry instead of rescheduling the same animation', () => {
+ render();
+ emit('keyboardWillShow');
+ emit('keyboardWillChangeFrame', keyboardEvent());
+ emit('keyboardDidChangeFrame', keyboardEvent());
+ emit('keyboardDidShow', keyboardEvent());
+ expect(native.schedule).toHaveBeenCalledTimes(1);
+ expect(native.configure).not.toHaveBeenCalled();
+ });
+
+ it('clears stale metrics when mounting between willHide and didHide', () => {
+ emit('keyboardDidShow');
+ emit('keyboardWillHide');
+ render();
+ expect(height()).toBe(300);
+ emit('keyboardDidHide');
+ expect(height()).toBe(0);
+ expect(padding()).toBe('0px');
+ expect(native.schedule).not.toHaveBeenCalled();
+ });
+
+ it('reconciles an opening keyboard whose willShow preceded mounting without replaying its animation', () => {
+ emit('keyboardWillShow');
+ render();
+ expect(height()).toBe(0);
+ emit('keyboardDidShow');
+ expect(height()).toBe(300);
+ expect(padding()).toBe('300px');
+ expect(native.schedule).not.toHaveBeenCalled();
+ });
+
+ it('reconciles a keyboard resize whose willChangeFrame preceded mounting', () => {
+ emit('keyboardDidShow');
+ emit('keyboardWillChangeFrame', keyboardEvent(444, 400));
+ render();
+ expect(height()).toBe(300);
+ emit('keyboardDidChangeFrame', keyboardEvent(444, 400));
+ expect(height()).toBe(400);
+ expect(native.schedule).not.toHaveBeenCalled();
+ });
+
+ it('preserves the cross-fade screenY=0 exception', async () => {
+ native.crossFade.mockResolvedValue(true);
+ render();
+ await act(async () => {
+ emit('keyboardWillShow', keyboardEvent(0, 844));
+ });
+ expect(height()).toBe(0);
+ expect(padding()).toBe('0px');
+ });
+
+ it('ignores an old cross-fade query after a newer keyboard frame', async () => {
+ let resolveCrossFade!: (value: boolean) => void;
+ native.crossFade.mockImplementation(
+ () =>
+ new Promise((resolve) => {
+ resolveCrossFade = resolve;
+ }),
+ );
+ render();
+ emit('keyboardWillShow', keyboardEvent(0, 844));
+ emit('keyboardWillChangeFrame', keyboardEvent(444, 400));
+ await act(async () => resolveCrossFade(true));
+ expect(height()).toBe(400);
+ });
+
+ it('does not flash a full-screen inset when mounting with cross-fade keyboard metrics', async () => {
+ native.shown = true;
+ native.metrics = keyboardEvent(0, 844).endCoordinates;
+ native.crossFade.mockResolvedValue(true);
+ render();
+ expect(padding()).toBe('0px');
+ await act(async () => {});
+ expect(height()).toBe(0);
+ });
+
+ it('does not add a card animation to a zero-duration keyboard update in the same commit', () => {
+ render();
+ act(() => {
+ for (const listener of native.listeners.get('keyboardWillShow') ?? []) {
+ listener(keyboardEvent(544, 300, 0));
+ }
+ root.render(<Harness active />);
+ });
+ expect(padding()).toBe('300px');
+ expect(native.configure).toHaveBeenCalledTimes(1);
+ expect(native.configure).toHaveBeenCalledWith({
+ duration: 0,
+ update: { duration: 0, type: 'linear' },
+ });
+ });
+
+ it.each([true, null])(
+ 'keeps geometry working without extra motion when reduce-motion is %s',
+ (reducedMotion) => {
+ native.reducedMotion = reducedMotion;
+ render();
+ render({ active: true });
+ expect(native.configure).not.toHaveBeenCalled();
+ emit('keyboardWillShow');
+ expect(height()).toBe(300);
+ expect(native.schedule).not.toHaveBeenCalled();
+ expect(native.configure).toHaveBeenLastCalledWith({
+ duration: 0,
+ update: { duration: 0, type: 'linear' },
+ });
+ },
+ );
+
+ it('animates a card before keyboard events arrive, then yields to actual keyboard timing', () => {
+ render();
+ render({ active: true });
+ expect(native.configure).toHaveBeenCalledWith(
+ expect.objectContaining({ duration: motionDuration.base }),
+ );
+ native.configure.mockClear();
+ emit('keyboardWillShow');
+ render({ active: false });
+ expect(native.configure).not.toHaveBeenCalled();
+ emit('keyboardWillHide');
+ expect(native.schedule).toHaveBeenCalledTimes(2);
+ });
+
+ it('uses the size-change token for standalone card transitions, without replaying old keyboard motion', () => {
+ const now = vi.spyOn(Date, 'now').mockReturnValue(1000);
+ render();
+ emit('keyboardWillShow');
+ now.mockReturnValue(2000);
+ render({ active: true });
+ expect(native.configure).toHaveBeenLastCalledWith(
+ expect.objectContaining({ duration: motionDuration.base }),
+ );
+ expect(native.schedule).toHaveBeenCalledTimes(1);
+ });
+
+ it('preserves Android did-events and KAV height behavior without adding another keyboard inset', () => {
+ native.platform.OS = 'android';
+ render({ inset: 24 });
+ emit('keyboardDidShow', keyboardEvent(544, 300, 0));
+ expect(height()).toBe(300);
+ expect(
+ container
+ .querySelector('[data-container="kav"]')
+ ?.getAttribute('data-behavior'),
+ ).toBe('height');
+ expect(padding()).toBe('');
+ expect(native.schedule).not.toHaveBeenCalled();
+ expect(native.configure).not.toHaveBeenCalled();
+ emit('keyboardDidHide');
+ expect(height()).toBe(0);
+ render({ active: true });
+ expect(native.configure).toHaveBeenLastCalledWith(
+ expect.objectContaining({ duration: motionDuration.base }),
+ );
+ });
+
+ it('mounts on web without native keyboard snapshot APIs or extra avoidance', () => {
+ native.platform.OS = 'web';
+ render({ inset: 34 });
+ expect(height()).toBe(0);
+ expect(container.querySelector('output')?.getAttribute('data-visible')).toBe('false');
+ expect(container.querySelector('[data-container="kav"]')).not.toBeNull();
+ expect(padding()).toBe('');
+ expect(native.schedule).not.toHaveBeenCalled();
+ });
+
+ it('removes every keyboard listener on unmount', () => {
+ render();
+ act(() => root.render(null));
+ expect(
+ [...native.listeners.values()].every((listeners) => listeners.size === 0),
+ ).toBe(true);
+ });
+});
diff --git a/apps/mobile/src/__tests__/mobileNativeShellLayout.test.ts b/apps/mobile/src/__tests__/mobileNativeShellLayout.test.ts
index 53f969e74b..4ec3f9cb0e 100644
--- a/apps/mobile/src/__tests__/mobileNativeShellLayout.test.ts
+++ b/apps/mobile/src/__tests__/mobileNativeShellLayout.test.ts
@@ -54,6 +54,23 @@ describe('mobileNativeShellLayout', () => {
expect(layout.contentMaxWidth).toBe(390);
});
+ it.each([100, 80, 79, 35, 34, 4, 0, 700])(
+ 'keeps the absolute composer above the keyboard at %s pt of actual overlap',
+ (keyboardHeight) => {
+ const layout = buildSessionNativeShellLayout({
+ attachmentPickerOpen: false,
+ keyboardHeight,
+ keyboardVisible: keyboardHeight > 0,
+ paletteOpen: false,
+ platform: 'ios',
+ safeAreaBottomInset: 34,
+ screenHeight: 844,
+ });
+ // 真实页面的绝对 bottom + 内层 safe area 是输入区距窗口底的总留白。
+ expect(layout.keyboardBottomInset + 34).toBe(Math.max(keyboardHeight, 34));
+ },
+ );
+
it('caps palettes independently from the composer so message history remains mounted', () => {
const layout = buildSessionNativeShellLayout({
attachmentPickerOpen: false,
diff --git a/apps/mobile/src/session/ComposerKeyboardAvoidingView.tsx b/apps/mobile/src/session/ComposerKeyboardAvoidingView.tsx
new file mode 100644
index 0000000000..6b1c77228a
--- /dev/null
+++ b/apps/mobile/src/session/ComposerKeyboardAvoidingView.tsx
@@ -0,0 +1,46 @@
+import {
+ KeyboardAvoidingView,
+ Platform,
+ View,
+ type KeyboardAvoidingViewProps,
+} from 'react-native';
+import type { MobileKeyboardState } from '@/session/useMobileKeyboardState';
+
+interface ComposerKeyboardAvoidingViewProps extends KeyboardAvoidingViewProps {
+ keyboard: MobileKeyboardState;
+ /** 全屏页面外层 SafeAreaView 已经扣除的底部高度,避免新建页重复上抬。 */
+ bottomInset?: number;
+}
+
+/**
+ * 任务 / 新建页都是无系统 header 的全屏布局。iOS 使用同一键盘状态控制底部
+ * 留白,让输入卡片尺寸与消息视口同批更新;Android 继续由 KAV 处理缩窗。
+ */
+export function ComposerKeyboardAvoidingView({
+ keyboard,
+ bottomInset = 0,
+ behavior,
+ keyboardVerticalOffset = 0,
+ enabled = true,
+ contentContainerStyle,
+ style,
+ ...props
+}: ComposerKeyboardAvoidingViewProps) {
+ if (Platform.OS === 'ios') {
+ const paddingBottom =
+ enabled && keyboard.visible
+ ? Math.max(0, keyboard.height - bottomInset + keyboardVerticalOffset)
+ : 0;
+ return <View {...props} style={[style, { paddingBottom }]} />;
+ }
+ return (
+ <KeyboardAvoidingView
+ {...props}
+ behavior={behavior}
+ contentContainerStyle={contentContainerStyle}
+ enabled={enabled}
+ keyboardVerticalOffset={keyboardVerticalOffset}
+ style={style}
+ />
+ );
+}
diff --git a/apps/mobile/src/session/mobileNativeShellLayout.ts b/apps/mobile/src/session/mobileNativeShellLayout.ts
index aa55ce6c51..00171c21f3 100644
--- a/apps/mobile/src/session/mobileNativeShellLayout.ts
+++ b/apps/mobile/src/session/mobileNativeShellLayout.ts
@@ -44,13 +44,16 @@ export function buildSessionNativeShellLayout(
screenWidth: input.screenWidth,
});
const { contentMaxWidth, contentWidth, landscape, shortViewport, wideViewport } = viewportLayout;
- const keyboardHeight = input.keyboardVisible
- ? Math.min(normalizeDimension(input.keyboardHeight, 0), Math.round(screenHeight * 0.62))
+ const keyboardOcclusion = input.keyboardVisible
+ ? normalizeDimension(input.keyboardHeight, 0)
: 0;
+ const keyboardHeight = Math.min(keyboardOcclusion, Math.round(screenHeight * 0.62));
const keyboardVisible = input.keyboardVisible && keyboardHeight >= MIN_KEYBOARD_VISIBLE_HEIGHT;
const safeAreaBottomInset = normalizeDimension(input.safeAreaBottomInset, 0);
- const keyboardBottomInset = input.platform === 'ios' && keyboardVisible
- ? Math.max(0, keyboardHeight - safeAreaBottomInset)
+ // 80pt 阈值与 62% 上限只用于内容密度策略。绝对定位的输入区必须一直
+ // 跟随实际遮挡,否则交互式收起跨过 80pt 时会突然落到仍未收完的键盘下面。
+ const keyboardBottomInset = input.platform === 'ios'
+ ? Math.max(0, keyboardOcclusion - safeAreaBottomInset)
: 0;
const availableHeight = Math.max(320, screenHeight - keyboardHeight);
const compactByKeyboard = keyboardVisible && availableHeight < screenHeight * 0.72;
diff --git a/apps/mobile/src/session/useComposerCardTransition.ts b/apps/mobile/src/session/useComposerCardTransition.ts
index d6b2e1fdcc..966dd8b776 100644
--- a/apps/mobile/src/session/useComposerCardTransition.ts
+++ b/apps/mobile/src/session/useComposerCardTransition.ts
@@ -1,14 +1,14 @@
import { useRef } from 'react';
import { LayoutAnimation, Platform, UIManager } from 'react-native';
+import { useReduceMotionEnabled } from '@/hooks/useReduceMotion';
+import { motionDuration } from '@/theme/tokens';
+import type { MobileKeyboardState } from '@/session/useMobileKeyboardState';
// 旧架构 Android 需要显式开启 LayoutAnimation;新架构(Fabric)下该开关是 no-op。
if (Platform.OS === 'android' && UIManager.setLayoutAnimationEnabledExperimental) {
UIManager.setLayoutAnimationEnabledExperimental(true);
}
-/** 与 iOS 键盘弹出动画同量级的时长,让卡片展开与键盘上滑视觉上是同一段运动。 */
-const CARD_TRANSITION_DURATION_MS = 250;
-
/**
* Composer 简洁态 ↔ 聚焦卡片态切换的布局过渡动画。
*
@@ -16,10 +16,9 @@ const CARD_TRANSITION_DURATION_MS = 250;
* (输入行变全宽、工具排出现 / 消失、卡片高度与圆角变化、消息列表 padding 联动)
* 整体平滑过渡,而不是硬切。
*
- * 切换入口分散(聚焦 / blur / 各面板 toggle / 语音状态异步变化),无法在每个
- * 事件处理器里注册;LayoutAnimation.configureNext 只是给下一次 native 布局
- * 提交打标记、并非副作用 setState,因此在 render 期间按状态翻转调用一次是
- * 安全且唯一集中的挂点(重复调用幂等)。
+ * 收到 iOS frame 的同一轮更新及键盘动画期间不配置另一条动画。焦点先于
+ * 键盘事件到达、硬件键盘或面板 / 语音切换时,保留普通尺寸过渡;后续键盘
+ * 事件取得动画控制权。沿用已有的 render 阶段布局提交前挂点。
*
* 三段动画的分工:
* - update:存活视图的位置 / 尺寸平滑(卡片长高、输入行变全宽、absolute 锚点的
@@ -27,14 +26,24 @@ const CARD_TRANSITION_DURATION_MS = 250;
* - create / delete(opacity):工具排按钮(加号 / 权限 / 模型 / 发送)只在
* 卡片态挂载,出现时在最终位置原地渐显、收起时原地渐隐,没有位移感。
*/
-export function useComposerCardTransition(cardActive: boolean): void {
- const prevRef = useRef(cardActive);
- if (prevRef.current !== cardActive) {
- prevRef.current = cardActive;
+export function useComposerCardTransition(
+ cardActive: boolean,
+ keyboard: MobileKeyboardState,
+): void {
+ const reduceMotion = useReduceMotionEnabled();
+ const transition = keyboard.transition.current;
+ const prevRef = useRef({ cardActive, transition });
+ const previous = prevRef.current;
+ prevRef.current = { cardActive, transition };
+ const keyboardOwnsTransition = Platform.OS === 'ios' && (
+ previous.transition !== transition
+ || (transition !== null && Date.now() - transition.startedAt < transition.event.duration)
+ );
+ if (previous.cardActive !== cardActive && !keyboardOwnsTransition && reduceMotion === false) {
LayoutAnimation.configureNext({
create: { property: 'opacity', type: 'easeInEaseOut' },
delete: { property: 'opacity', type: 'easeInEaseOut' },
- duration: CARD_TRANSITION_DURATION_MS,
+ duration: motionDuration.base,
update: { type: 'easeInEaseOut' },
});
}
diff --git a/apps/mobile/src/session/useMobileKeyboardState.ts b/apps/mobile/src/session/useMobileKeyboardState.ts
index c68dc8e1bb..c865e9e6f5 100644
--- a/apps/mobile/src/session/useMobileKeyboardState.ts
+++ b/apps/mobile/src/session/useMobileKeyboardState.ts
@@ -1,35 +1,134 @@
-import { useEffect, useState } from 'react';
-import { Keyboard, Platform, type KeyboardEvent } from 'react-native';
+import { useEffect, useLayoutEffect, useRef, useState, type RefObject } from 'react';
+import {
+ AccessibilityInfo,
+ Keyboard,
+ LayoutAnimation,
+ Platform,
+ useWindowDimensions,
+ type KeyboardEvent,
+ type KeyboardMetrics,
+} from 'react-native';
import type { LoginKeyboardRect } from '@/auth/loginKeyboardAvoidance';
+import { isDockedKeyboard } from '@/auth/loginKeyboardAvoidance';
+import { getCachedReduceMotionEnabled } from '@/hooks/useReduceMotion';
+
+export interface MobileKeyboardState {
+ /** 窗口底部实际被遮挡的高度,交互式收起时不等于键盘自身高度。 */
+ height: number;
+ visible: boolean;
+ /** 事件先配置动画再更新布局;卡片切换据此让出同一次布局的动画控制权。 */
+ transition: RefObject<{ event: KeyboardEvent; startedAt: number } | null>;
+}
/**
* 跟踪软键盘的可见性与高度。
*
- * iOS 用 will 事件在动画开始前拿到目标高度,Android 只有 did 事件。
- * 从会话页提取的共享 hook,供需要按键盘高度计算可用空间的页面复用。
+ * iOS 的输入卡片、消息区域和避让容器共用这份坐标与动画,不再让 KAV
+ * 另行监听 show/hide 并覆盖动画。Android 保留 KAV 的 did 事件避让。
*/
-export function useMobileKeyboardState(): { height: number; visible: boolean } {
- const [state, setState] = useState({ height: 0, visible: false });
+export function useMobileKeyboardState(): MobileKeyboardState {
+ const viewport = useWindowDimensions();
+ const [state, setState] = useState(() => {
+ // Web 的 Keyboard shim 没有原生几何快照 API,沿用零占位初值。
+ if (Platform.OS === 'web') return { shown: false, frame: null };
+ const frame = Keyboard.metrics() ?? null;
+ return {
+ shown: Keyboard.isVisible(),
+ // 已开键盘时导航进来,也先排除 cross-fade 的 screenY=0 特例。
+ frame: Platform.OS === 'ios' && frame?.screenY === 0 ? null : frame,
+ };
+ });
+ const snapshot = useRef(state);
+ const transition = useRef<MobileKeyboardState['transition']['current']>(null);
- useEffect(() => {
- const showEvent = Platform.OS === 'ios' ? 'keyboardWillShow' : 'keyboardDidShow';
- const hideEvent = Platform.OS === 'ios' ? 'keyboardWillHide' : 'keyboardDidHide';
- const showSubscription = Keyboard.addListener(showEvent, (event) => {
- setState({
- height: event.endCoordinates?.height ?? 0,
- visible: true,
- });
- });
- const hideSubscription = Keyboard.addListener(hideEvent, () => {
- setState({ height: 0, visible: false });
- });
+ useLayoutEffect(() => {
+ let disposed = false;
+ let shown = snapshot.current.shown;
+ let latestEvent: KeyboardEvent | null = null;
+ const publish = (event: KeyboardEvent, frame: KeyboardMetrics | null) => {
+ // cross-fade 查询晚于 hide / 下一次 frame 返回时,不得恢复旧键盘占位。
+ if (disposed || latestEvent !== event) return;
+ const previous = snapshot.current;
+ if (previous.shown === shown && sameKeyboardFrame(previous.frame, frame)) return;
+ const next = { shown, frame };
+ snapshot.current = next;
+ transition.current = { event, startedAt: Date.now() };
+ if (Platform.OS === 'ios') {
+ if (getCachedReduceMotionEnabled() === false && event.duration > 0) {
+ Keyboard.scheduleLayoutAnimation(event);
+ } else {
+ // 零时长是直接跟手;也清掉同一帧此前可能排入的卡片动画。
+ LayoutAnimation.configureNext({ duration: 0, update: { duration: 0, type: 'linear' } });
+ }
+ }
+ setState(next);
+ };
+ const update = (event: KeyboardEvent) => {
+ latestEvent = event;
+ if (Platform.OS === 'ios' && shown && event.endCoordinates.screenY === 0) {
+ // 保留 RN KAV 的系统交叉淡化兼容:此时 screenY=0 不是全屏遮挡。
+ void AccessibilityInfo.prefersCrossFadeTransitions()
+ .then((crossFade) => publish(event, crossFade ? null : event.endCoordinates))
+ .catch(() => publish(event, event.endCoordinates));
+ } else {
+ publish(event, shown ? event.endCoordinates : null);
+ }
+ };
+ const subscriptions = [
+ Keyboard.addListener(
+ Platform.OS === 'ios' ? 'keyboardWillShow' : 'keyboardDidShow',
+ (event) => { shown = true; update(event); },
+ ),
+ Keyboard.addListener(
+ Platform.OS === 'ios' ? 'keyboardWillHide' : 'keyboardDidHide',
+ (event) => { shown = false; update(event); },
+ ),
+ ];
+ if (Platform.OS === 'ios') {
+ subscriptions.push(Keyboard.addListener('keyboardWillChangeFrame', (event) => {
+ // undock 会先 frame 再 hide;hide 后的 frame 不能独自重新显示键盘。
+ if (shown) update(event);
+ }));
+ // 导航可发生在 will 与 did 之间;RN 的 metrics 缓存只在 did 时更新。
+ // 最终事件负责补齐挂载前错过的变化,时长归零避免把已结束的动画重播。
+ subscriptions.push(
+ Keyboard.addListener('keyboardDidShow', (event) => {
+ shown = true;
+ update({ ...event, duration: 0 });
+ }),
+ Keyboard.addListener('keyboardDidHide', (event) => {
+ shown = false;
+ update({ ...event, duration: 0 });
+ }),
+ Keyboard.addListener('keyboardDidChangeFrame', (event) => {
+ if (shown) update({ ...event, duration: 0 });
+ }),
+ );
+ const initialFrame = Keyboard.metrics();
+ if (shown && initialFrame?.screenY === 0) {
+ update({ duration: 0, easing: 'keyboard', endCoordinates: initialFrame });
+ }
+ }
return () => {
- showSubscription.remove();
- hideSubscription.remove();
+ disposed = true;
+ for (const subscription of subscriptions) subscription.remove();
};
}, []);
- return state;
+ const frame = state.shown ? state.frame : null;
+ const height = !frame ? 0 : Platform.OS === 'ios'
+ ? 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
+ : Math.max(0, frame.height);
+ return { height, visible: height > 0, transition };
+}
+
+function sameKeyboardFrame(a: KeyboardMetrics | null, b: KeyboardMetrics | null): boolean {
+ return a === b || (a !== null && b !== null
+ && a.screenX === b.screenX && a.screenY === b.screenY
+ && a.width === b.width && a.height === b.height);
}
/** 登录键盘契约的完整矩形状态(visible + endCoordinates 矩形)。 */