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): token 速度面板打开时不再挡住聊天记录滚动

Dash4fad4bdb8377
diff --git a/apps/mobile/app/_layout.tsx b/apps/mobile/app/_layout.tsx
index a4305e6ae9..d77e606a84 100644
--- a/apps/mobile/app/_layout.tsx
+++ b/apps/mobile/app/_layout.tsx
@@ -38,6 +38,7 @@ import {
} from '@/device-link/DeviceLinkContext';
import { PushNotificationsBridge } from '@/notifications/PushNotificationsBridge';
import { GestureHandlerRootView } from '@/platform/gestureHandler';
+import { OutsideTapProvider } from '@/platform/OutsideTap';
// import 即同步完成 i18next init;必须先于任何 t() 消费方挂载。
import '@/i18n';
import { LocaleProvider } from '@/i18n/useLocale';
@@ -446,6 +447,7 @@ function RootLayout() {
}
return (
<GestureHandlerRootView style={styles.gestureRoot}>
+ <OutsideTapProvider>
<SafeAreaProvider>
<AdaptiveWindowProvider>
<ThemeProvider>
@@ -467,6 +469,7 @@ function RootLayout() {
</ThemeProvider>
</AdaptiveWindowProvider>
</SafeAreaProvider>
+ </OutsideTapProvider>
</GestureHandlerRootView>
);
}
diff --git a/apps/mobile/src/__tests__/outsideTap.test.tsx b/apps/mobile/src/__tests__/outsideTap.test.tsx
new file mode 100644
index 0000000000..7e54300ac3
--- /dev/null
+++ b/apps/mobile/src/__tests__/outsideTap.test.tsx
@@ -0,0 +1,99 @@
+// @vitest-environment jsdom
+import { act, createElement } from "react";
+import { createRoot, type Root } from "react-dom/client";
+import { afterEach, beforeEach, expect, it, vi } from "vitest";
+import { OutsideTapProvider, useOutsideTap } from "@/platform/OutsideTap";
+
+const harness = vi.hoisted(() => ({
+ root: {} as Record<string, (event: any) => void>,
+}));
+vi.mock("react-native", () => ({
+ View: (props: any) => {
+ harness.root = props;
+ return createElement("div", {}, props.children);
+ },
+}));
+
+let root: Root;
+const onOutsideTap = vi.fn();
+function Floating({ active }: { active: boolean }) {
+ // The floating card occupies x/y 100..200.
+ useOutsideTap(
+ active,
+ (x, y) => x >= 100 && x <= 200 && y >= 100 && y <= 200,
+ onOutsideTap,
+ );
+ return null;
+}
+const render = (active = true) =>
+ act(async () =>
+ root.render(
+ createElement(
+ OutsideTapProvider,
+ null,
+ createElement(Floating, { active }),
+ ),
+ ),
+ );
+const touch = (
+ name: "onTouchStart" | "onTouchMove" | "onTouchEnd" | "onTouchCancel",
+ pageX = 0,
+ pageY = 0,
+ fingers = name === "onTouchEnd" || name === "onTouchCancel" ? 0 : 1,
+) =>
+ harness.root[name]({
+ nativeEvent: { pageX, pageY, touches: Array.from({ length: fingers }) },
+ });
+const tap = (x: number, y: number) => {
+ touch("onTouchStart", x, y);
+ touch("onTouchEnd", x, y);
+};
+
+beforeEach(() => {
+ Object.assign(globalThis, { IS_REACT_ACT_ENVIRONMENT: true });
+ onOutsideTap.mockReset();
+ root = createRoot(document.createElement("div"));
+});
+afterEach(async () => {
+ await act(async () => root.unmount());
+});
+
+it("reports taps outside the floating area and ignores taps inside it", async () => {
+ await render();
+ tap(150, 150);
+ expect(onOutsideTap).not.toHaveBeenCalled();
+ tap(20, 400);
+ expect(onOutsideTap).toHaveBeenCalledTimes(1);
+});
+
+it("lets scrolls, drags, pinches and cancelled touches pass without closing", async () => {
+ await render();
+ // Scroll the conversation underneath.
+ touch("onTouchStart", 20, 400);
+ touch("onTouchMove", 20, 300);
+ touch("onTouchEnd", 20, 300);
+ // A native scroll view taking over the gesture.
+ touch("onTouchStart", 20, 400);
+ touch("onTouchCancel");
+ touch("onTouchEnd", 20, 400);
+ // Two-finger gesture.
+ touch("onTouchStart", 20, 400);
+ touch("onTouchStart", 60, 400, 2);
+ touch("onTouchEnd", 60, 400, 1);
+ touch("onTouchEnd", 20, 400);
+ expect(onOutsideTap).not.toHaveBeenCalled();
+ // Small jitter still counts as a tap.
+ touch("onTouchStart", 20, 400);
+ touch("onTouchMove", 24, 403);
+ touch("onTouchEnd", 24, 403);
+ expect(onOutsideTap).toHaveBeenCalledTimes(1);
+});
+
+it("stops listening once the floating area closes", async () => {
+ await render(false);
+ tap(20, 400);
+ await render(true);
+ await render(false);
+ tap(20, 400);
+ expect(onOutsideTap).not.toHaveBeenCalled();
+});
diff --git a/apps/mobile/src/__tests__/runningTokenRatePopover.test.tsx b/apps/mobile/src/__tests__/runningTokenRatePopover.test.tsx
index 0e38c576e7..709799c9f6 100644
--- a/apps/mobile/src/__tests__/runningTokenRatePopover.test.tsx
+++ b/apps/mobile/src/__tests__/runningTokenRatePopover.test.tsx
@@ -23,8 +23,12 @@ const harness = vi.hoisted(() => ({
anchor: { x: 220, y: 600, width: 80 },
insets: { top: 24, bottom: 16, left: 0, right: 0 },
press: {} as Record<string, (...args: any[]) => void>,
- backdrop: {} as Record<string, (...args: any[]) => void>,
card: {} as Record<string, (...args: any[]) => void>,
+ outsideTap: null as null | {
+ contains: (x: number, y: number) => boolean;
+ onOutsideTap: () => void;
+ },
+ back: null as null | (() => boolean),
}));
vi.mock("react-native", () => {
const view = ({ children, testID }: any) =>
@@ -43,20 +47,40 @@ vi.mock("react-native", () => {
if (props.testID === "session.tokenRate.card") harness.card = props;
return view(props);
}),
- Modal: ({ visible, children }: any) =>
- visible ? createElement("div", {}, children) : null,
+ BackHandler: {
+ addEventListener: (_: string, handler: () => boolean) => {
+ harness.back = handler;
+ return { remove: () => (harness.back = null) };
+ },
+ },
useWindowDimensions: () => harness.window,
ScrollView: view,
Text: view,
StyleSheet: { create: (s: unknown) => s },
Pressable: (props: any) => {
- if (props.testID === "session.tokenRate.backdrop")
- harness.backdrop = props;
- else harness.press = props;
+ harness.press = props;
return view(props);
},
};
});
+vi.mock("@/platform/OutsideTap", async () => {
+ const { useEffect } = await import("react");
+ return {
+ useOutsideTap: (
+ active: boolean,
+ contains: (x: number, y: number) => boolean,
+ onOutsideTap: () => void,
+ ) => {
+ useEffect(() => {
+ if (!active) return;
+ harness.outsideTap = { contains, onOutsideTap };
+ return () => {
+ harness.outsideTap = null;
+ };
+ });
+ },
+ };
+});
vi.mock("react-native-safe-area-context", () => ({
useSafeAreaInsets: () => harness.insets,
}));
@@ -273,27 +297,39 @@ it("toggles on tap, holds only until release, and does not turn the long-press r
expect(card()).not.toBeNull();
});
-it("dismisses on outside tap, but not card taps or swipes", async () => {
+it("floats without a backdrop and dismisses only on taps outside the card and trigger", async () => {
await render();
+ await gesture("onPressIn");
await gesture("onPress");
expect(harness.card.onStartShouldSetResponder()).toBe(true);
+ expect(harness.card.pointerEvents).toBe("auto");
expect(card()).not.toBeNull();
+ await act(async () =>
+ harness.card.onLayout({ nativeEvent: { layout: { height: 120 } } }),
+ );
+ const style = Object.assign({}, ...(harness.card as any).style);
+ const cardX = style.left + harness.anchor.x;
+ const cardY = style.top + harness.anchor.y;
+ const tap = harness.outsideTap!;
+ // Taps on the card or its trigger keep it open.
+ expect(tap.contains(cardX + 10, cardY + 10)).toBe(true);
+ expect(tap.contains(harness.anchor.x + 10, harness.anchor.y + 10)).toBe(true);
+ expect(tap.contains(20, 20)).toBe(false);
+ await act(async () => tap.onOutsideTap());
+ expect(card()).toBeNull();
+ expect(harness.outsideTap).toBeNull();
+ await gesture("onPressIn");
+ await gesture("onPress");
+ let handled = false;
await act(async () => {
- harness.backdrop.onPressIn({ nativeEvent: { pageX: 20, pageY: 20 } });
- harness.backdrop.onTouchMove({ nativeEvent: { pageX: 20, pageY: 80 } });
- harness.backdrop.onPress();
- });
- expect(card()).not.toBeNull();
- await act(async () => {
- harness.backdrop.onPressIn({ nativeEvent: { pageX: 20, pageY: 20 } });
- harness.backdrop.onPress();
+ handled = harness.back!();
});
+ expect(handled).toBe(true);
expect(card()).toBeNull();
await gesture("onPressIn");
await gesture("onLongPress");
- expect(
- host.querySelector('[data-testid="session.tokenRate.backdrop"]'),
- ).toBeNull();
+ expect(harness.card.pointerEvents).toBe("none");
+ expect(harness.outsideTap).toBeNull();
await gesture("onTouchCancel");
expect(card()).toBeNull();
});
@@ -335,8 +371,8 @@ it.each(["onPress", "onLongPress"])(
harness.card.onLayout({ nativeEvent: { layout: { height } } }),
);
const style = Object.assign({}, ...(harness.card as any).style);
- const x = style.left + (open === "onLongPress" ? harness.anchor.x : 0);
- const top = style.top + (open === "onLongPress" ? y : 0);
+ const x = style.left + harness.anchor.x;
+ const top = style.top + y;
expect(x).toBeGreaterThanOrEqual(harness.insets.left);
expect(x + style.width).toBeLessThanOrEqual(800 - harness.insets.right);
expect(top).toBeGreaterThanOrEqual(harness.insets.top);
@@ -370,8 +406,8 @@ it.each(["onPress", "onLongPress"])("keeps %s in the composer's fold/occlusion r
const height = style.maxHeight;
await act(async () => harness.card.onLayout({ nativeEvent: { layout: { height } } }));
style = Object.assign({}, ...(harness.card as any).style);
- const x = style.left + (open === "onLongPress" ? harness.anchor.x : 0);
- const y = style.top + (open === "onLongPress" ? harness.anchor.y : 0);
+ const x = style.left + harness.anchor.x;
+ const y = style.top + harness.anchor.y;
expect(x).toBeGreaterThanOrEqual(region.x);
expect(y).toBeGreaterThanOrEqual(region.y);
expect(x + style.width).toBeLessThanOrEqual(region.x + region.width);
diff --git a/apps/mobile/src/platform/OutsideTap.tsx b/apps/mobile/src/platform/OutsideTap.tsx
new file mode 100644
index 0000000000..bbe1997654
--- /dev/null
+++ b/apps/mobile/src/platform/OutsideTap.tsx
@@ -0,0 +1,92 @@
+import {
+ createContext,
+ useContext,
+ useEffect,
+ useRef,
+ type ReactNode,
+} from "react";
+import { View, type GestureResponderEvent } from "react-native";
+
+type OutsideTapListener = {
+ /** Window coordinates, same space as `measureInWindow` and touch pageX/pageY. */
+ contains: (x: number, y: number) => boolean;
+ onOutsideTap: () => void;
+};
+
+type Subscribe = (listener: OutsideTapListener) => () => void;
+
+const OutsideTapContext = createContext<Subscribe>(() => () => {});
+
+/** Movement beyond this is a drag or scroll, not a tap. */
+export const OUTSIDE_TAP_SLOP = 8;
+
+/**
+ * Observes raw touches without claiming the responder, so floating panels can
+ * close on an outside tap while everything underneath keeps scrolling normally.
+ */
+export function OutsideTapProvider({ children }: { children: ReactNode }) {
+ const listeners = useRef(new Set<OutsideTapListener>());
+ const touch = useRef<{ x: number; y: number; moved: boolean } | null>(null);
+ const subscribe = useRef<Subscribe>((listener) => {
+ listeners.current.add(listener);
+ return () => listeners.current.delete(listener);
+ }).current;
+ return (
+ <OutsideTapContext.Provider value={subscribe}>
+ <View
+ style={{ flex: 1 }}
+ onTouchStart={(event: GestureResponderEvent) => {
+ const { pageX, pageY, touches } = event.nativeEvent;
+ // A second finger turns the gesture into a pinch; never a tap.
+ if (touches.length > 1 && touch.current) touch.current.moved = true;
+ else
+ touch.current = { x: pageX, y: pageY, moved: touches.length > 1 };
+ }}
+ onTouchMove={(event: GestureResponderEvent) => {
+ const start = touch.current;
+ if (
+ start &&
+ Math.hypot(
+ event.nativeEvent.pageX - start.x,
+ event.nativeEvent.pageY - start.y,
+ ) > OUTSIDE_TAP_SLOP
+ )
+ start.moved = true;
+ }}
+ onTouchEnd={(event: GestureResponderEvent) => {
+ if (event.nativeEvent.touches.length > 0) return;
+ const start = touch.current;
+ touch.current = null;
+ if (!start || start.moved) return;
+ for (const listener of [...listeners.current]) {
+ if (!listener.contains(start.x, start.y)) listener.onOutsideTap();
+ }
+ }}
+ // Native scroll views cancel JS touches when they take over the gesture.
+ onTouchCancel={() => {
+ touch.current = null;
+ }}
+ >
+ {children}
+ </View>
+ </OutsideTapContext.Provider>
+ );
+}
+
+/** While active, calls `onOutsideTap` for taps that start outside `contains`. */
+export function useOutsideTap(
+ active: boolean,
+ contains: OutsideTapListener["contains"],
+ onOutsideTap: () => void,
+) {
+ const subscribe = useContext(OutsideTapContext);
+ const latest = useRef({ contains, onOutsideTap });
+ latest.current = { contains, onOutsideTap };
+ useEffect(() => {
+ if (!active) return;
+ return subscribe({
+ contains: (x, y) => latest.current.contains(x, y),
+ onOutsideTap: () => latest.current.onOutsideTap(),
+ });
+ }, [active, subscribe]);
+}
diff --git a/apps/mobile/src/session/RunningTokenRatePopover.tsx b/apps/mobile/src/session/RunningTokenRatePopover.tsx
index 5f6af7a099..39ea5aa799 100644
--- a/apps/mobile/src/session/RunningTokenRatePopover.tsx
+++ b/apps/mobile/src/session/RunningTokenRatePopover.tsx
@@ -1,6 +1,6 @@
import { useEffect, useRef, useState, type ReactNode } from "react";
import {
- Modal,
+ BackHandler,
Pressable,
ScrollView,
StyleSheet,
@@ -28,6 +28,7 @@ import {
typeScale,
} from "@/theme/tokens";
import { usePaneViewport } from "@/platform/AdaptiveWindowContext";
+import { useOutsideTap } from "@/platform/OutsideTap";
import { useSafeAreaInsets } from "react-native-safe-area-context";
import type { LayoutRect } from "@/platform/windowGeometry";
@@ -73,13 +74,12 @@ export function RunningTokenRatePopover({
const window = useWindowDimensions();
const insets = useSafeAreaInsets();
const anchorRef = useRef<View>(null);
- const [anchor, setAnchor] = useState({ x: 0, y: 0, width: 0 });
+ const [anchor, setAnchor] = useState({ x: 0, y: 0, width: 0, height: 0 });
const [cardHeight, setCardHeight] = useState(0);
const measureAnchor = () =>
- anchorRef.current?.measureInWindow((x, y, width) => {
- setAnchor({ x, y, width });
+ anchorRef.current?.measureInWindow((x, y, width, height) => {
+ setAnchor({ x, y, width, height });
});
- const outsideTouch = useRef({ x: 0, y: 0, moved: false });
// The composer owns region selection, including folds, occlusions and keyboard.
const region = availableRegion ?? {
x: insets.left,
@@ -95,10 +95,7 @@ export function RunningTokenRatePopover({
region.width - spacing.lg * 2,
),
);
- const maxCardHeight = Math.max(
- 1,
- region.height - spacing.lg * 2,
- );
+ const maxCardHeight = Math.max(1, region.height - spacing.lg * 2);
const cardLeft = Math.max(
region.x + spacing.lg,
Math.min(
@@ -133,6 +130,40 @@ export function RunningTokenRatePopover({
region.height,
],
);
+ // Pinned cards float without a backdrop: the conversation keeps scrolling
+ // underneath, and only a tap outside the card and its trigger closes it.
+ const within = (
+ x: number,
+ y: number,
+ rect: { x: number; y: number; width: number; height: number },
+ ) =>
+ x >= rect.x &&
+ x <= rect.x + rect.width &&
+ y >= rect.y &&
+ y <= rect.y + rect.height;
+ useOutsideTap(
+ mode === "pinned",
+ (x, y) =>
+ within(x, y, anchor) ||
+ within(x, y, {
+ x: cardLeft,
+ y: cardTop,
+ width: cardWidth,
+ height: cardHeight,
+ }),
+ () => setMode("closed"),
+ );
+ useEffect(() => {
+ if (mode !== "pinned") return;
+ const subscription = BackHandler.addEventListener(
+ "hardwareBackPress",
+ () => {
+ setMode("closed");
+ return true;
+ },
+ );
+ return () => subscription.remove();
+ }, [mode]);
const longPressed = useRef(false);
const touchStart = useRef<{ x: number; y: number } | null>(null);
const [internalHistory, setInternalHistory] = useState(() => {
@@ -151,7 +182,13 @@ export function RunningTokenRatePopover({
generationReliable,
}),
);
- }, [managedHistory, startedAt, outputTokens, generationDurationMs, generationReliable]);
+ }, [
+ managedHistory,
+ startedAt,
+ outputTokens,
+ generationDurationMs,
+ generationReliable,
+ ]);
const history = managedHistory ?? internalHistory;
useEffect(() => {
if (managedHistory) return;
@@ -209,8 +246,8 @@ export function RunningTokenRatePopover({
{
width: cardWidth,
maxHeight: maxCardHeight,
- left: cardLeft - (mode === "held" ? anchor.x : 0),
- top: cardTop - (mode === "held" ? anchor.y : 0),
+ left: cardLeft - anchor.x,
+ top: cardTop - anchor.y,
opacity: cardHeight > 0 ? 1 : 0,
},
]}
@@ -341,57 +378,13 @@ export function RunningTokenRatePopover({
>
{children}
</Pressable>
- {mode === "held" && card}
- <Modal
- supportedOrientations={[
- "portrait",
- "portrait-upside-down",
- "landscape-left",
- "landscape-right",
- ]}
- visible={mode === "pinned"}
- transparent
- animationType="none"
- statusBarTranslucent
- navigationBarTranslucent
- onRequestClose={() => setMode("closed")}
- >
- <View style={styles.overlay}>
- <Pressable
- testID="session.tokenRate.backdrop"
- style={StyleSheet.absoluteFill}
- accessible={false}
- onPressIn={(event) => {
- outsideTouch.current = {
- x: event.nativeEvent.pageX,
- y: event.nativeEvent.pageY,
- moved: false,
- };
- }}
- onTouchMove={(event) => {
- const start = outsideTouch.current;
- if (
- Math.hypot(
- event.nativeEvent.pageX - start.x,
- event.nativeEvent.pageY - start.y,
- ) > 8
- )
- start.moved = true;
- }}
- onPress={() => {
- if (!outsideTouch.current.moved) setMode("closed");
- }}
- />
- {card}
- </View>
- </Modal>
+ {mode !== "closed" && card}
</View>
);
}
const makeStyles = (colors: ThemeColors) =>
StyleSheet.create({
- overlay: { flex: 1 },
anchor: { position: "relative", flexShrink: 0 },
trigger: {
minHeight: 44,