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): 横屏键盘保留桌面缩放并居中鼠标

Dash7cc27a3f91de
diff --git a/apps/mobile/src/remote-desktop/RemoteDesktopScreen.tsx b/apps/mobile/src/remote-desktop/RemoteDesktopScreen.tsx
index 938cc8f218..15e1819cc1 100644
--- a/apps/mobile/src/remote-desktop/RemoteDesktopScreen.tsx
+++ b/apps/mobile/src/remote-desktop/RemoteDesktopScreen.tsx
@@ -12,6 +12,7 @@ import {
StatusBar,
Keyboard,
KeyboardAvoidingView,
+ type KeyboardEvent,
Platform,
Pressable,
ScrollView,
@@ -217,6 +218,13 @@ export default function RemoteDesktopScreen() {
const [fullKeys, setFullKeys] = useState(false);
const [keyboardFocusRequest, setKeyboardFocusRequest] = useState(0);
const [nativeKeyboard, setNativeKeyboard] = useState(false);
+ const [nativeKeyboardHeight, setNativeKeyboardHeight] = useState(0);
+ const [keyboardPanelHeight, setKeyboardPanelHeight] = useState(0);
+ // Android's system keyboard already resizes the window. Keep its existing
+ // flow layout; only iOS needs an offset above the native keyboard.
+ const landscapeKeyboardOverlay = landscape && (Platform.OS === "ios" || fullKeys);
+ const keyboardBottom = Platform.OS === "ios" && keyboard && !fullKeys
+ ? nativeKeyboardHeight : 0;
const heldKeys = useRef(new Map<string, string[]>());
const [keyPage, setKeyPage] = useState(0);
const [comboMode, setComboMode] = useState(true);
@@ -282,14 +290,25 @@ export default function RemoteDesktopScreen() {
}
};
useEffect(() => {
- const show = Keyboard.addListener("keyboardDidShow", () => {
- setNativeKeyboard(true);
+ const updateFrame = (event: KeyboardEvent) => {
+ const height = Math.max(
+ 0,
+ Dimensions.get("screen").height - event.endCoordinates.screenY,
+ );
+ setNativeKeyboardHeight(height);
+ setNativeKeyboard(height > 0);
+ };
+ const show = Keyboard.addListener("keyboardDidShow", updateFrame);
+ const frame = Platform.OS === "ios"
+ ? Keyboard.addListener("keyboardWillChangeFrame", updateFrame)
+ : null;
+ const hide = Keyboard.addListener("keyboardDidHide", () => {
+ setNativeKeyboard(false);
+ setNativeKeyboardHeight(0);
});
- const hide = Keyboard.addListener("keyboardDidHide", () =>
- setNativeKeyboard(false),
- );
return () => {
show.remove();
+ frame?.remove();
hide.remove();
};
}, []);
@@ -640,7 +659,11 @@ export default function RemoteDesktopScreen() {
useEffect(() => {
send({
type: "mouseButtons",
- bottomInset: !keyboard && !landscape ? toolbarSize.height : 0,
+ bottomInset:
+ keyboard && landscapeKeyboardOverlay
+ ? keyboardPanelHeight + keyboardBottom
+ : !keyboard && !landscape ? toolbarSize.height : 0,
+ keyboardOpen: keyboard && landscapeKeyboardOverlay,
rightInset: !keyboard && landscape ? toolbarSize.width : 0,
leftInset: landscape ? insets.left : 0,
enabled:
@@ -659,6 +682,9 @@ export default function RemoteDesktopScreen() {
showMouseButtons,
insets.left,
toolbarSize,
+ keyboardPanelHeight,
+ landscapeKeyboardOverlay,
+ keyboardBottom,
landscape,
focused,
operations,
@@ -1083,6 +1109,8 @@ export default function RemoteDesktopScreen() {
);
return (
<KeyboardAvoidingView
+ testID="remoteDesktop.layout"
+ enabled={!landscapeKeyboardOverlay}
behavior={Platform.OS === "ios" ? "padding" : undefined}
style={styles.root}
>
@@ -1331,8 +1359,13 @@ export default function RemoteDesktopScreen() {
)}
{keyboard && (
<View
+ testID="remoteDesktop.keyboardPanel"
+ onLayout={({ nativeEvent: { layout } }) =>
+ setKeyboardPanelHeight(layout.height)
+ }
style={[
styles.keyboard,
+ landscapeKeyboardOverlay && [styles.keyboardOverlay, { bottom: keyboardBottom }],
{
paddingLeft: Math.max(spacing.xs, edgePadding.paddingLeft),
paddingRight: Math.max(spacing.sm, edgePadding.paddingRight),
@@ -1626,8 +1659,9 @@ const makeStyles = (colors: ThemeColors) =>
},
disabled: { opacity: 0.4 },
buttonText: { color: colors.textPrimary, fontSize: typeScale.caption },
+ keyboardOverlay: { position: "absolute", left: 0, right: 0 },
keyboard: {
- backgroundColor: colors.surface,
+ backgroundColor: colors.surfaceTranslucent,
paddingHorizontal: spacing.sm,
borderTopWidth: StyleSheet.hairlineWidth,
borderTopColor: colors.border,
diff --git a/apps/mobile/src/remote-desktop/__tests__/screen.test.tsx b/apps/mobile/src/remote-desktop/__tests__/screen.test.tsx
index 0b4e44e235..b4e2fb624d 100644
--- a/apps/mobile/src/remote-desktop/__tests__/screen.test.tsx
+++ b/apps/mobile/src/remote-desktop/__tests__/screen.test.tsx
@@ -7,6 +7,9 @@ import { AppState } from "react-native";
import { goBackGuarded } from "@/utils/backGuard";
const fixture = vi.hoisted(() => ({
+ platform: "ios",
+ keyboardListeners: {} as Record<string, (event: unknown) => void>,
+ views: {} as Record<string, any>,
invoke: vi.fn(),
openLink: vi.fn(),
post: vi.fn(),
@@ -22,8 +25,9 @@ const fixture = vi.hoisted(() => ({
}));
vi.mock("react-native", async () => {
const { createElement } = await import("react");
- const view = (tag: string) => (p: any) =>
- createElement(
+ const view = (tag: string) => (p: any) => {
+ if (p.testID) fixture.views[p.testID] = p;
+ return createElement(
tag,
{
onClick: p.onPress,
@@ -34,8 +38,10 @@ vi.mock("react-native", async () => {
},
p.children,
);
+ };
return {
View: view("div"),
+ Modal: (p: any) => p.visible ? createElement("div", {}, p.children) : null,
Pressable: view("button"),
ScrollView: view("div"),
KeyboardAvoidingView: view("div"),
@@ -53,10 +59,16 @@ vi.mock("react-native", async () => {
return { remove() {} };
},
},
- Keyboard: { dismiss() {}, addListener: () => ({ remove() {} }) },
+ Keyboard: {
+ dismiss() {},
+ addListener: (name: string, listener: (event: unknown) => void) => {
+ fixture.keyboardListeners[name] = listener;
+ return { remove() {} };
+ },
+ },
Dimensions: { get: () => fixture.size },
useWindowDimensions: () => fixture.size,
- Platform: { OS: "ios" },
+ Platform: { get OS() { return fixture.platform; } },
};
});
vi.mock("@/components/AppText", () => ({
@@ -92,6 +104,7 @@ vi.mock("lucide-react-native", () => ({
VolumeX: () => null,
PictureInPicture2: () => null,
Check: () => null,
+ ClipboardList: () => null,
ChevronDown: () => null,
ChevronRight: () => null,
Eye: () => null,
@@ -143,6 +156,7 @@ vi.mock("react-native-webview", () => ({
fixture.crashed = p.onContentProcessDidTerminate;
useImperativeHandle(ref, () => ({
postMessage: fixture.post,
+ requestFocus() {},
reload: fixture.reload,
}));
return createElement("div", { "data-testid": p.testID });
@@ -160,6 +174,9 @@ const button = (key: string) =>
beforeEach(() => {
(globalThis as any).IS_REACT_ACT_ENVIRONMENT = true;
vi.clearAllMocks();
+ fixture.platform = "ios";
+ fixture.views = {};
+ fixture.keyboardListeners = {};
vi.useFakeTimers();
fixture.focused = true;
fixture.status = "online";
@@ -211,6 +228,51 @@ const connect = async () => {
};
describe("remote desktop controls", () => {
+ it("overlays landscape keyboards and includes their measured occlusion", async () => {
+ fixture.size = { width: 844, height: 390 };
+ act(() => root.render(<RemoteDesktopScreen />));
+ await connect();
+ act(() => button("keyboard").click());
+ expect(fixture.views["remoteDesktop.layout"].enabled).toBe(false);
+ const panel = () => fixture.views["remoteDesktop.keyboardPanel"];
+ expect(panel().style.flat(Infinity)).toContainEqual(expect.objectContaining({ position: "absolute" }));
+ act(() => panel().onLayout({ nativeEvent: { layout: { height: 60 } } }));
+ act(() => fixture.keyboardListeners.keyboardWillChangeFrame({ endCoordinates: { screenY: 180 } }));
+ expect(panel().style.flat(Infinity)).toContainEqual({ bottom: 210 });
+ expect(sent().filter((m) => m.type === "mouseButtons").at(-1)).toMatchObject({
+ bottomInset: 270, keyboardOpen: true,
+ });
+ const computer = [...host.querySelectorAll("button")].find((element) => element.textContent === "remoteDesktop.computerKeyboard")!;
+ act(() => computer.click());
+ act(() => panel().onLayout({ nativeEvent: { layout: { height: 280 } } }));
+ expect(panel().style.flat(Infinity)).toContainEqual({ bottom: 0 });
+ expect(sent().filter((m) => m.type === "mouseButtons").at(-1)).toMatchObject({
+ bottomInset: 280, keyboardOpen: true,
+ });
+ act(() => button("close").click());
+ expect(sent().filter((m) => m.type === "mouseButtons").at(-1)).toMatchObject({
+ bottomInset: 0, keyboardOpen: false,
+ });
+ });
+
+ it("keeps Android native keyboard avoidance without adding its height twice", async () => {
+ fixture.platform = "android";
+ fixture.size = { width: 844, height: 390 };
+ act(() => root.render(<RemoteDesktopScreen />));
+ await connect();
+ act(() => button("keyboard").click());
+ const panel = () => fixture.views["remoteDesktop.keyboardPanel"];
+ act(() => fixture.keyboardListeners.keyboardDidShow({ endCoordinates: { screenY: 180 } }));
+ act(() => panel().onLayout({ nativeEvent: { layout: { height: 60 } } }));
+ expect(panel().style.flat(Infinity)).not.toContainEqual(expect.objectContaining({ position: "absolute" }));
+ expect(sent().filter((m) => m.type === "mouseButtons").at(-1)).toMatchObject({ bottomInset: 0, keyboardOpen: false });
+ const computer = [...host.querySelectorAll("button")].find((element) => element.textContent === "remoteDesktop.computerKeyboard")!;
+ act(() => computer.click());
+ act(() => panel().onLayout({ nativeEvent: { layout: { height: 280 } } }));
+ expect(panel().style.flat(Infinity)).toContainEqual({ bottom: 0 });
+ expect(sent().filter((m) => m.type === "mouseButtons").at(-1)).toMatchObject({ bottomInset: 280, keyboardOpen: true });
+ });
+
it("keeps a video answer arriving after control initialization and ignores it after exit", async () => {
const original = fixture.invoke.getMockImplementation()!;
let control!: (value: object) => void;
diff --git a/apps/mobile/src/remote-desktop/__tests__/viewer.test.ts b/apps/mobile/src/remote-desktop/__tests__/viewer.test.ts
index 9526670151..baabec655b 100644
--- a/apps/mobile/src/remote-desktop/__tests__/viewer.test.ts
+++ b/apps/mobile/src/remote-desktop/__tests__/viewer.test.ts
@@ -306,6 +306,45 @@ describe("remote desktop viewport", () => {
expect(v.elements.image.style.width).toBe("400px");
expect(parseFloat(v.elements.image.style.top)).toBeGreaterThan(0);
});
+ it.each([1, 2])("keeps landscape scale %sx and centers the cursor above keyboard overlays", (scale) => {
+ const v = viewer();
+ v.elements.stage.clientWidth = 800;
+ v.elements.stage.clientHeight = 400;
+ v.send({ type: "init", epoch: "keyboard", width: 1920, height: 1080, fillHeight: true });
+ if (scale === 2) {
+ v.pointer("pointerdown", 1, 200, 200);
+ v.pointer("pointerdown", 2, 400, 200);
+ v.pointer("pointermove", 1, 100, 200);
+ v.pointer("pointermove", 2, 500, 200);
+ v.frame();
+ v.frame(40);
+ v.pointer("pointerup", 1, 100, 200);
+ v.pointer("pointerup", 2, 500, 200);
+ }
+ v.send({ type: "frame", jpeg: "", cursor: {
+ x: .9, y: .85, width: 18, height: 18, hotX: 9, hotY: 9,
+ visible: true, png: "iVBORw0KGgo=",
+ } });
+ const width = v.elements.image.style.width;
+ expect(parseFloat(v.elements.image.style.height)).toBeCloseTo(400 * scale);
+ // Header, computer keyboard, phone keyboard, and closing the keyboard.
+ for (const bottomInset of [60, 260, 300, 0]) {
+ v.send({ type: "mouseButtons", keyboardOpen: bottomInset > 0, bottomInset, leftInset: 50, rightInset: 0 });
+ v.blur();
+ for (let i = 0; i < 30; i++) v.frame();
+ const image = v.elements.image.style;
+ expect(image.width).toBe(width);
+ expect(parseFloat(image.height)).toBeCloseTo(400 * scale);
+ expect(parseFloat(image.left) + .9 * parseFloat(image.width)).toBeCloseTo(425);
+ expect(parseFloat(image.top) + .85 * parseFloat(image.height)).toBeCloseTo((400 - bottomInset) / 2);
+ }
+ });
+ it("does not recenter portrait content for a keyboard overlay message", () => {
+ const v = viewer();
+ const before = { ...v.elements.image.style };
+ v.send({ type: "mouseButtons", keyboardOpen: true, bottomInset: 260 });
+ expect(v.elements.image.style).toEqual(before);
+ });
it("initializes when the native engine cannot serialize function source", () => {
const stringify = vi
.spyOn(Function.prototype, "toString")
diff --git a/apps/mobile/src/remote-desktop/viewerHtml.ts b/apps/mobile/src/remote-desktop/viewerHtml.ts
index 7973630584..9271b33d3f 100644
--- a/apps/mobile/src/remote-desktop/viewerHtml.ts
+++ b/apps/mobile/src/remote-desktop/viewerHtml.ts
@@ -79,7 +79,7 @@ const VIEWER_SCRIPT = String.raw`
const post=(message)=>window.ReactNativeWebView.postMessage(JSON.stringify({...message,epoch}));
const clamp=(v)=>Math.max(0,Math.min(1,v));
let fillHeight=false;
- let panAnimation=null,viewportRightInset=0,viewportLeftInset=0,viewportBottomInset=0;
+ let panAnimation=null,viewportRightInset=0,viewportLeftInset=0,viewportBottomInset=0,keyboardViewportInset=0;
let cursorNeedsEntry=true,manualViewMoved=false,followRest=null;
// Insets guide centering and pan limits without clipping the full-screen
// video surface or adding an opaque strip beside the Dynamic Island.
@@ -322,7 +322,16 @@ const VIEWER_SCRIPT = String.raw`
case 'resume':if(video.srcObject)video.play().catch(()=>{});break;
case 'releaseInput':release();break;
case 'theme':if(/^#[0-9a-f]{3,8}$/i.test(message.surface)){document.body.style.background=message.surface;document.documentElement.style.setProperty('--surface',message.surface);}if(/^#[0-9a-f]{3,8}$/i.test(message.foreground)){cursor.style.borderColor=message.foreground;document.documentElement.style.setProperty('--foreground',message.foreground);}break;
- case 'mouseButtons':if(Number.isFinite(message.bottomInset))viewportBottomInset=Math.max(0,Math.min(stage.clientHeight-1,message.bottomInset));if(Number.isFinite(message.leftInset)){const left=Math.max(0,Math.min(stage.clientWidth-1,message.leftInset));if(left!==viewportLeftInset){viewportLeftInset=left;settlePan();render();}}if(Number.isFinite(message.rightInset)){const inset=Math.max(0,Math.min(stage.clientWidth-1,message.rightInset));if(inset!==viewportRightInset){viewportRightInset=inset;settlePan();render();}}if(!message.enabled){for(const button of heldMouse.keys())queue({kind:'button',button,down:false,x:cx,y:cy});heldMouse.clear();resetWheel();flush();}for(const [edge,value] of [['bottom',message.bottomInset],['right',message.rightInset]])if(Number.isFinite(value)&&value>=0&&value<=4096)mouseButtons.style[edge]=value+'px';showMouseButtons=message.enabled===true;for(const name of ['left','right','wheel'])if(typeof message.labels?.[name]==='string')document.getElementById('mouse-'+name).setAttribute('aria-label',message.labels[name]);updateMouseButtons();break;
+ case 'mouseButtons':if(Number.isFinite(message.bottomInset))viewportBottomInset=Math.max(0,Math.min(stage.clientHeight-1,message.bottomInset));if(Number.isFinite(message.leftInset)){const left=Math.max(0,Math.min(stage.clientWidth-1,message.leftInset));if(left!==viewportLeftInset){viewportLeftInset=left;settlePan();render();}}if(Number.isFinite(message.rightInset)){const inset=Math.max(0,Math.min(stage.clientWidth-1,message.rightInset));if(inset!==viewportRightInset){viewportRightInset=inset;settlePan();render();}}const keyboardInset=fillHeight&&message.keyboardOpen===true?viewportBottomInset:0;
+ if(keyboardInset!==keyboardViewportInset){
+ const wasOpen=keyboardViewportInset>0;keyboardViewportInset=keyboardInset;
+ if(fillHeight&&(keyboardInset>0||wasOpen)){
+ stopPanAnimation();const r=layout(),v=cursorViewport();
+ place((v.minX+v.maxX)/2-cx*r.width,(v.minY+v.maxY)/2-cy*r.height,r);
+ followRest={fx,fy,zoom};cursorNeedsEntry=false;manualViewMoved=false;render();
+ }
+ }
+ if(!message.enabled){for(const button of heldMouse.keys())queue({kind:'button',button,down:false,x:cx,y:cy});heldMouse.clear();resetWheel();flush();}for(const [edge,value] of [['bottom',message.bottomInset],['right',message.rightInset]])if(Number.isFinite(value)&&value>=0&&value<=4096)mouseButtons.style[edge]=value+'px';showMouseButtons=message.enabled===true;for(const name of ['left','right','wheel'])if(typeof message.labels?.[name]==='string')document.getElementById('mouse-'+name).setAttribute('aria-label',message.labels[name]);updateMouseButtons();break;
case 'init':followRest=null;cursorNeedsEntry=true;stopPanAnimation();resetCursor();control=false;release();pending=[];sending=false;seq=0;epoch=message.epoch;dw=message.width;dh=message.height;fillHeight=message.fillHeight===true;video.muted=!message.audio;render();connect();break;
case 'viewport':fillHeight=message.fillHeight===true;release();render();break;
case 'answer':if(pc){const current=pc;pc.setRemoteDescription({type:'answer',sdp:message.sdp}).catch(()=>{if(pc===current){closeRtc();post({type:'fallback'});}});}break;