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): 重写图片 lightbox 缩放平移手势 (#3608)

Dash56b7b9a929c2
diff --git a/apps/mobile/src/__tests__/imageLightboxModel.test.ts b/apps/mobile/src/__tests__/imageLightboxModel.test.ts
index 326a83da4a..de53f5357c 100644
--- a/apps/mobile/src/__tests__/imageLightboxModel.test.ts
+++ b/apps/mobile/src/__tests__/imageLightboxModel.test.ts
@@ -3,15 +3,26 @@ import {
LIGHTBOX_DOUBLE_TAP_SCALE,
LIGHTBOX_MAX_SCALE,
LIGHTBOX_MIN_SCALE,
+ LIGHTBOX_TAP_MAX_DISTANCE,
+ bakeLightboxOrigin,
canShareLightboxImage,
+ compensateLightboxOrigin,
clampLightboxScale,
clampLightboxTranslation,
+ clampLightboxVisualPan,
+ isLightboxZoomed,
lightboxBackgroundOpacity,
+ lightboxContainedSize,
+ lightboxDoubleTapTranslate,
lightboxImageLayers,
lightboxInitialIndex,
lightboxPageIndex,
lightboxPageLabel,
+ lightboxPanOverflow,
+ lightboxPinchOrigin,
nextDoubleTapScale,
+ reclampLightboxPan,
+ shouldCloseLightboxOnTap,
shouldDismissLightbox,
} from '@/session/imageLightboxModel';
@@ -31,6 +42,70 @@ describe('imageLightboxModel', () => {
expect(clampLightboxTranslation(-250, 400, 2)).toBe(-200);
});
+ it('clamps translation against the contained image size, not the letterbox', () => {
+ // 横图 contain 进 400×800:显示 400×200。2x 后高 400,相对 800 高仍无溢出
+ expect(lightboxContainedSize(400, 800, 800, 400)).toEqual({ width: 400, height: 200 });
+ expect(lightboxPanOverflow(800, 200, 2)).toBe(0);
+ expect(clampLightboxTranslation(80, 800, 2, 200)).toBe(0);
+ // 竖图 contain 进 400×800:显示 400×800。2x 后宽溢出 200
+ expect(lightboxContainedSize(400, 800, 400, 800)).toEqual({ width: 400, height: 800 });
+ expect(clampLightboxTranslation(250, 400, 2, 400)).toBe(200);
+ // 自然尺寸未知时退回容器
+ expect(lightboxContainedSize(400, 800, 0, 0)).toEqual({ width: 400, height: 800 });
+ });
+
+ it('reclamps leftover pan when contain size shrinks after natural size arrives', () => {
+ // 未知尺寸按 400×800 铺满,2x 后 Y 仍能平移 80;横图 onLoad 后显示 400×200,Y 溢出变 0
+ expect(clampLightboxTranslation(80, 800, 2, 800)).toBe(80);
+ expect(reclampLightboxPan(0, 80, 400, 800, 2, 400, 200)).toEqual({ x: 0, y: 0 });
+ // 旋转 / 变窄时 X 同样立刻收回,不把旧位移留到下一次拖动
+ expect(reclampLightboxPan(250, 0, 400, 800, 2, 400, 800)).toEqual({ x: 200, y: 0 });
+ });
+
+ it('distinguishes reclamping the double-tap target from an in-flight intermediate', () => {
+ // 双击目标 150,动画走到 80 时竖图 overflow 仍是 200:钳中间值会把目标改成 80
+ // (动画停早,点击点漂向中心)。动画中必须钳 saved 目标,不能钳 live。
+ // 调用方不得用这个新目标另起 withTiming:那会跟仍在跑的 scale 抢默认时长。
+ expect(reclampLightboxPan(80, 0, 400, 800, 2, 400, 800)).toEqual({ x: 80, y: 0 });
+ expect(reclampLightboxPan(150, 0, 400, 800, 2, 400, 800)).toEqual({ x: 150, y: 0 });
+ });
+
+ it('bakes pinch origin into translation so resetting origin does not jump', () => {
+ expect(lightboxPinchOrigin(300, 400)).toBe(100);
+ // translate 40, origin 100, scale 2 → 40 + 100 * (1-2) = -60
+ expect(bakeLightboxOrigin(40, 100, 2)).toBe(-60);
+ expect(bakeLightboxOrigin(-60, 0, 2)).toBe(-60);
+ });
+
+ it('compensates translation when applying a pinch origin onto an existing scale', () => {
+ // 双击 2.5x 后 translate=-150;再在 origin=100 处捏合,补偿后画面公式不变
+ expect(compensateLightboxOrigin(-150, 100, LIGHTBOX_DOUBLE_TAP_SCALE)).toBe(0);
+ expect(bakeLightboxOrigin(0, 100, LIGHTBOX_DOUBLE_TAP_SCALE)).toBe(-150);
+ // 1x 时 origin 项为 0,补偿是空操作
+ expect(compensateLightboxOrigin(0, 100, 1)).toBe(0);
+ });
+
+ it('clamps baked visual pan then compensates when origin is nonzero', () => {
+ // origin=0: bake/补偿恒等,与直接钳 raw 相同
+ expect(clampLightboxVisualPan(250, 0, 0, 0, 400, 800, 2, 400, 800)).toEqual({ x: 200, y: 0 });
+ // origin=100, scale=2: visual = T + 100*(1-2) = T-100。T=-200 钳 raw 看似贴边,
+ // 画面却在 -300,越出 overflow 200。只修捏合、不修标注 pan 的半边修法过不了这条。
+ expect(clampLightboxTranslation(-200, 400, 2, 400)).toBe(-200);
+ expect(clampLightboxVisualPan(-200, 0, 100, 0, 400, 800, 2, 400, 800)).toEqual({ x: -100, y: 0 });
+ expect(bakeLightboxOrigin(-100, 100, 2)).toBe(-200);
+ // 画面未越界时 raw 保持不动
+ expect(clampLightboxVisualPan(250, 0, 100, 0, 400, 800, 2, 400, 800)).toEqual({ x: 250, y: 0 });
+ });
+
+ it('double-tap zooms into the tap point and resets when returning to 1x', () => {
+ expect(isLightboxZoomed(1)).toBe(false);
+ expect(isLightboxZoomed(1.005)).toBe(false);
+ expect(isLightboxZoomed(2.5)).toBe(true);
+ // tap 300 in 400-wide view, 2.5x: origin 100 → 100 * (1-2.5) = -150
+ expect(lightboxDoubleTapTranslate(300, 400, LIGHTBOX_DOUBLE_TAP_SCALE)).toBe(-150);
+ expect(lightboxDoubleTapTranslate(300, 400, 1)).toBe(0);
+ });
+
it('dismisses on distance or fling velocity', () => {
expect(shouldDismissLightbox(121, 0)).toBe(true);
expect(shouldDismissLightbox(-121, 0)).toBe(true);
@@ -38,6 +113,26 @@ describe('imageLightboxModel', () => {
expect(shouldDismissLightbox(20, 100)).toBe(false);
});
+ it('keeps tap-to-close slop tight enough that a pan is not a tap', () => {
+ expect(LIGHTBOX_TAP_MAX_DISTANCE).toBeGreaterThan(0);
+ expect(LIGHTBOX_TAP_MAX_DISTANCE).toBeLessThan(40);
+ });
+
+ it('closes on tap only at 1x', () => {
+ expect(shouldCloseLightboxOnTap(1)).toBe(true);
+ expect(shouldCloseLightboxOnTap(1.005)).toBe(true);
+ expect(shouldCloseLightboxOnTap(LIGHTBOX_DOUBLE_TAP_SCALE)).toBe(false);
+ expect(shouldCloseLightboxOnTap(2)).toBe(false);
+ });
+
+ it('never dismisses while zoomed, even past distance or fling', () => {
+ // 放大后平移(含纵向无溢出的横图)不能变成下滑关闭
+ expect(shouldDismissLightbox(200, 0, LIGHTBOX_DOUBLE_TAP_SCALE)).toBe(false);
+ expect(shouldDismissLightbox(20, 900, 2)).toBe(false);
+ expect(shouldDismissLightbox(200, 900, LIGHTBOX_MIN_SCALE)).toBe(true);
+ expect(shouldDismissLightbox(200, 0, 1.005)).toBe(true);
+ });
+
it('fades the backdrop with drag progress', () => {
expect(lightboxBackgroundOpacity(0, 800)).toBe(1);
expect(lightboxBackgroundOpacity(200, 800)).toBeCloseTo(1 - 0.5 * 0.7);
diff --git a/apps/mobile/src/__tests__/messageMediaThumbnailWiring.test.ts b/apps/mobile/src/__tests__/messageMediaThumbnailWiring.test.ts
index bb4e0c9530..64c7c5041d 100644
--- a/apps/mobile/src/__tests__/messageMediaThumbnailWiring.test.ts
+++ b/apps/mobile/src/__tests__/messageMediaThumbnailWiring.test.ts
@@ -93,7 +93,30 @@ describe('mobile message media thumbnail wiring', () => {
const lightboxSource = readTextLf(resolve(process.cwd(), 'src/session/ImageLightbox.tsx'), 'utf8');
expect(lightboxSource).toContain('message.imageLightbox');
expect(lightboxSource).toContain('shouldDismissLightbox');
+ expect(lightboxSource).toContain('shouldCloseLightboxOnTap');
expect(lightboxSource).toContain('Gesture.Pinch()');
+ // 单击关闭必须限制位移:RNGH Tap 默认 maxDist 无限,短拖松手会关 lightbox
+ expect(lightboxSource).toContain('maxDistance(LIGHTBOX_TAP_MAX_DISTANCE)');
+ // 自然尺寸到达后按新 contain 边界立刻重钳位移,不把 letterbox 估算的旧平移留到下次拖动
+ expect(lightboxSource).toContain('reclampLightboxPan(');
+ // 双击 withTiming 未结束时只重钳 saved 目标,不另起 withTiming 跟 scale 抢时长
+ expect(lightboxSource).toContain('if (doubleTapBusy.value)');
+ expect(lightboxSource).toContain('双击动画中只改 saved');
+ const doubleTapReclamp = lightboxSource.slice(
+ lightboxSource.indexOf('双击动画中只改 saved'),
+ lightboxSource.indexOf('const next = reclampLightboxPan(\n translateX.value'),
+ );
+ expect(doubleTapReclamp).not.toContain('withTiming(');
+ expect(lightboxSource).toContain('if (!finished || !doubleTapBusy.value) return');
+ // 二次捏合:已有缩放时先补偿 origin,不把 origin*(1-scale) 立刻叠进画面
+ expect(lightboxSource).toContain('compensateLightboxOrigin(');
+ // origin≠0 时平移钳的是 bake 后的画面,浏览捏合与标注双指 pan 共用
+ expect(lightboxSource).toContain('clampLightboxVisualPan(');
+ // chrome 显隐走共享 motion token,不在组件里写死毫秒
+ expect(lightboxSource).toContain('duration: motionDuration.instant');
+ expect(lightboxSource).toContain('duration: motionDuration.fast');
+ // 下滑半途改捏合:fail 不走 onEnd,必须在 onFinalize 清掉 dragY/dismissY
+ expect(lightboxSource).toContain('onFinalize((_event, success)');
// 分享按产品决策走系统分享单;expo-sharing 必须动态 import(旧构建缺原生模块)
const screenShare = screenSource.includes("await import('expo-sharing')");
expect(screenShare).toBe(true);
diff --git a/apps/mobile/src/session/ImageLightbox.tsx b/apps/mobile/src/session/ImageLightbox.tsx
index 1b247a60fa..63f86298b2 100644
--- a/apps/mobile/src/session/ImageLightbox.tsx
+++ b/apps/mobile/src/session/ImageLightbox.tsx
@@ -2,9 +2,11 @@
* ImageLightbox — IM 级全屏图片查看器。
* ---------------------------------------------------------------------------
* 点缩略图直接全屏黑底看图,交互对齐主流 IM:
- * - 双指捏合缩放(1x~4x)、放大后单指平移(钳制在图片边界内)
- * - 双击在 1x / 2.5x 间切换;单击关闭(微信式,产品决策)
+ * - 双指捏合绕焦点缩放(1x~4x);放大后单指平移(钳制在 contain 后的图片边界内)
+ * - 双击在 1x / 2.5x 间切换并落到点击点;1x 单击关闭
* - 1x 下竖直下滑跟手关闭(位移 + 背景渐隐),横滑翻会话内图片集
+ * - 放大后单指只平移;单击不关(双击缩回,或先回到 1x 再单击/下滑)
+ * - 捏合/平移期间 chrome 让位(不抢触摸),结束后恢复
* - chrome 极简:右下系统分享、多图时顶部页码;无关闭按钮(单击 / 下滑即关)、无文件名无正文
* 手势判定全部走 imageLightboxModel.ts 纯函数;取件复用会话屏的队列 + 磁盘缓存
* (onResolveRemoteMedia),点开时通常已被列表缩略图取过、秒出。
@@ -28,7 +30,7 @@ import {
import { Text } from '@/components/AppText';
import { MessageSquarePlus, Pen, Share as ShareIcon, Undo2, X } from 'lucide-react-native';
import Svg, { Path } from 'react-native-svg';
-import { fontWeight, iconSize, iconStroke, radius, typeScale } from '@/theme';
+import { fontWeight, iconSize, iconStroke, motionDuration, radius, typeScale } from '@/theme';
import { Gesture, GestureDetector, GestureHandlerRootView } from '@/platform/gestureHandler';
import Animated, {
runOnJS,
@@ -47,15 +49,25 @@ import {
type ResolveRemoteMediaFn,
} from '@/session/remoteMedia';
import {
+ bakeLightboxOrigin,
canShareLightboxImage,
+ compensateLightboxOrigin,
clampLightboxScale,
clampLightboxTranslation,
+ clampLightboxVisualPan,
+ isLightboxZoomed,
lightboxBackgroundOpacity,
+ lightboxContainedSize,
+ lightboxDoubleTapTranslate,
lightboxImageLayers,
lightboxInitialIndex,
lightboxPageIndex,
lightboxPageLabel,
+ lightboxPinchOrigin,
+ LIGHTBOX_TAP_MAX_DISTANCE,
nextDoubleTapScale,
+ reclampLightboxPan,
+ shouldCloseLightboxOnTap,
shouldDismissLightbox,
} from '@/session/imageLightboxModel';
import {
@@ -170,6 +182,8 @@ export const ImageLightbox = memo(function ImageLightbox({
const urls = useMemo(() => images.map((image) => image.url), [images]);
const [activeIndex, setActiveIndex] = useState(() => lightboxInitialIndex(urls, initialUrl));
const [zoomed, setZoomed] = useState(false);
+ /** 捏合/平移进行中 chrome 不接收触摸,避免底栏抢走双指。 */
+ const [chromeInteractive, setChromeInteractive] = useState(true);
const [resolveMap, setResolveMap] = useState<Record<string, PageResolveState>>({});
/**
* trimmed url → 列表缩略图地址(渐进出图的垫底层)。独立于 resolveMap:
@@ -178,6 +192,11 @@ export const ImageLightbox = memo(function ImageLightbox({
const [previewMap, setPreviewMap] = useState<Record<string, string>>({});
/** 下滑拖动量(当前活跃页写入),驱动背景与 chrome 渐隐。 */
const dismissY = useSharedValue(0);
+ /** 捏合/平移期间把 chrome 透明度打到 0;与 dismissY 相乘。 */
+ const chromeHidden = useSharedValue(0);
+ const handleChromeBusy = useCallback((busy: boolean) => {
+ setChromeInteractive(!busy);
+ }, []);
// ---- 圈点标注状态(仅活跃页;笔迹归一化存储,显示/烧录共用同一映射)----
const [isAnnotating, setIsAnnotating] = useState(false);
@@ -379,6 +398,9 @@ export const ImageLightbox = memo(function ImageLightbox({
const backdropStyle = useAnimatedStyle(() => ({
opacity: lightboxBackgroundOpacity(dismissY.value, height),
}));
+ const chromeStyle = useAnimatedStyle(() => ({
+ opacity: lightboxBackgroundOpacity(dismissY.value, height) * (1 - chromeHidden.value),
+ }));
const activeImage = images[activeIndex] ?? null;
const activeUri = activeImage ? displayUriFor(activeImage) : null;
@@ -483,10 +505,12 @@ export const ImageLightbox = memo(function ImageLightbox({
annotationStrokes={index === activeIndex
? strokes
: annotation?.initialStrokesFor?.(item) ?? EMPTY_STROKES}
+ chromeHidden={chromeHidden}
dismissY={dismissY}
height={height}
image={item}
naturalSize={naturalSizes[item.key] ?? null}
+ onChromeBusy={handleChromeBusy}
onDrawPoint={handleDrawPoint}
onImageError={handleImageLoadError}
onNaturalSize={handleNaturalSize}
@@ -504,8 +528,8 @@ export const ImageLightbox = memo(function ImageLightbox({
windowSize={3}
/>
<Animated.View
- pointerEvents="box-none"
- style={[styles.chrome, backdropStyle, { paddingBottom: insets.bottom + 16, paddingTop: insets.top + 8 }]}
+ pointerEvents={chromeInteractive ? 'box-none' : 'none'}
+ style={[styles.chrome, chromeStyle, { paddingBottom: insets.bottom + 16, paddingTop: insets.top + 8 }]}
>
{isAnnotating ? (
// 标注模式 chrome(对齐桌面):底部工具栏切换为 取消 / 撤销 / 提交
@@ -694,10 +718,12 @@ const LightboxPage = memo(function LightboxPage({
annotating,
annotationDraftStroke,
annotationStrokes,
+ chromeHidden,
dismissY,
height,
image,
naturalSize,
+ onChromeBusy,
onDrawPoint,
onImageError,
onNaturalSize,
@@ -716,11 +742,14 @@ const LightboxPage = memo(function LightboxPage({
annotationDraftStroke: AnnotationStroke | null;
/** 已落笔迹(活跃页=编辑态;其它页=各自的既有笔迹,只读叠加显示)。 */
annotationStrokes: readonly AnnotationStroke[];
+ chromeHidden: SharedValue<number>;
dismissY: SharedValue<number>;
height: number;
image: MobileMessageGalleryImage;
/** 图片自然尺寸(overlay 坐标基准;未知时 overlay 不渲染、画笔不采点)。 */
naturalSize: { width: number; height: number } | null;
+ /** 捏合/平移开始与结束时通知父层开关 chrome 触摸。 */
+ onChromeBusy(busy: boolean): void;
/** 画笔事件(容器坐标 + 当页 transform 快照),UI 线程经 runOnJS 上抛。 */
onDrawPoint: (
phase: 'start' | 'move' | 'end',
@@ -750,8 +779,16 @@ const LightboxPage = memo(function LightboxPage({
const translateY = useSharedValue(0);
const savedTranslateX = useSharedValue(0);
const savedTranslateY = useSharedValue(0);
+ const originX = useSharedValue(0);
+ const originY = useSharedValue(0);
+ const startFocalX = useSharedValue(0);
+ const startFocalY = useSharedValue(0);
+ const displayedW = useSharedValue(width);
+ const displayedH = useSharedValue(height);
+ const pinchBusy = useSharedValue(0);
+ const panBusy = useSharedValue(0);
+ const doubleTapBusy = useSharedValue(0);
const dragY = useSharedValue(0);
- const [pageZoomed, setPageZoomed] = useState(false);
/**
* 已 onLoad 成功的原图地址。存地址而不是 boolean:换图 / 强制重取换 url 后
* 天然失效,不需要额外 effect 复位(漏复位就会让新图那段又回到纯黑)。
@@ -781,11 +818,54 @@ const LightboxPage = memo(function LightboxPage({
fullFailedTerminally: !retryable && !!uri && failedFullUri === uri,
});
- const setZoomedBoth = useCallback((value: boolean) => {
- setPageZoomed(value);
+ const reportZoomed = useCallback((value: boolean) => {
onZoomChange(value);
}, [onZoomChange]);
+ useEffect(() => {
+ const size = lightboxContainedSize(
+ width,
+ height,
+ naturalSize?.width ?? 0,
+ naturalSize?.height ?? 0,
+ );
+ displayedW.value = size.width;
+ displayedH.value = size.height;
+ // 捏合中 onChange 每帧按新 displayed 钳;不能改 savedTranslate,否则下一帧
+ // 会用被改过的起点 + 焦点增量跳一下。
+ if (pinchBusy.value) return;
+ // 双击动画中只改 saved;live 仍归原 withTiming,结束回调再贴齐。
+ // 中途另起 withTiming 会跟 scale 抢默认时长:缩放先到、点击点随后横漂。
+ if (doubleTapBusy.value) {
+ const next = reclampLightboxPan(
+ savedTranslateX.value,
+ savedTranslateY.value,
+ width,
+ height,
+ savedScale.value,
+ size.width,
+ size.height,
+ );
+ savedTranslateX.value = next.x;
+ savedTranslateY.value = next.y;
+ return;
+ }
+ const next = reclampLightboxPan(
+ translateX.value,
+ translateY.value,
+ width,
+ height,
+ scale.value,
+ size.width,
+ size.height,
+ );
+ translateX.value = next.x;
+ translateY.value = next.y;
+ savedTranslateX.value = next.x;
+ savedTranslateY.value = next.y;
+ // eslint-disable-next-line react-hooks/exhaustive-deps
+ }, [naturalSize, width, height]);
+
// 翻走 / 换图时复位缩放与位移,避免回到本页时残留上次的缩放态。
useEffect(() => {
if (active) return;
@@ -795,82 +875,238 @@ const LightboxPage = memo(function LightboxPage({
translateY.value = 0;
savedTranslateX.value = 0;
savedTranslateY.value = 0;
+ originX.value = 0;
+ originY.value = 0;
+ pinchBusy.value = 0;
+ panBusy.value = 0;
+ doubleTapBusy.value = 0;
dragY.value = 0;
- setPageZoomed(false);
+ chromeHidden.value = 0;
+ onChromeBusy(false);
// 共享值的写入不需要依赖追踪,这里只关心 active 翻转时机
// eslint-disable-next-line react-hooks/exhaustive-deps
}, [active]);
const gesture = useMemo(() => {
+ const hideChrome = () => {
+ 'worklet';
+ chromeHidden.value = withTiming(1, { duration: motionDuration.instant });
+ runOnJS(onChromeBusy)(true);
+ };
+ const maybeShowChrome = () => {
+ 'worklet';
+ if (pinchBusy.value || panBusy.value) return;
+ chromeHidden.value = withTiming(0, { duration: motionDuration.fast });
+ runOnJS(onChromeBusy)(false);
+ };
+ const bakePinchOrigin = () => {
+ 'worklet';
+ const bakedX = bakeLightboxOrigin(translateX.value, originX.value, scale.value);
+ const bakedY = bakeLightboxOrigin(translateY.value, originY.value, scale.value);
+ originX.value = 0;
+ originY.value = 0;
+ if (!isLightboxZoomed(scale.value)) {
+ scale.value = withTiming(1);
+ savedScale.value = 1;
+ translateX.value = withTiming(0);
+ translateY.value = withTiming(0);
+ savedTranslateX.value = 0;
+ savedTranslateY.value = 0;
+ runOnJS(reportZoomed)(false);
+ return;
+ }
+ const cx = clampLightboxTranslation(bakedX, width, scale.value, displayedW.value);
+ const cy = clampLightboxTranslation(bakedY, height, scale.value, displayedH.value);
+ translateX.value = cx;
+ translateY.value = cy;
+ savedTranslateX.value = cx;
+ savedTranslateY.value = cy;
+ savedScale.value = scale.value;
+ runOnJS(reportZoomed)(true);
+ };
+
+ // 焦点捏合:起点锁定 origin,缩放绕焦点;浏览态跟手质心,标注态只改 scale
+ // (平移交给双指 pan,避免 Simultaneous 下位移被加两遍)。
const pinch = Gesture.Pinch()
- .onUpdate((event) => {
+ .onStart((event) => {
+ pinchBusy.value = 1;
+ doubleTapBusy.value = 0;
+ hideChrome();
+ // 捏合一开始就锁死翻页,不等 JS zoomed 提交;否则松手后立刻左右拖
+ // 会被 pagingEnabled 的 FlatList 抢走,当前页直接滑走。
+ runOnJS(reportZoomed)(true);
+ // 下滑半途改捏合:关掉正在进行的 dismiss 位移,不把图和背景留在半透明上。
+ dragY.value = 0;
+ dismissY.value = 0;
+ savedScale.value = scale.value;
+ originX.value = lightboxPinchOrigin(event.focalX, width);
+ originY.value = lightboxPinchOrigin(event.focalY, height);
+ // 已放大时 origin 会立刻贡献 origin*(1-scale);扣掉等量位移,二次捏合不跳。
+ translateX.value = compensateLightboxOrigin(translateX.value, originX.value, scale.value);
+ translateY.value = compensateLightboxOrigin(translateY.value, originY.value, scale.value);
+ savedTranslateX.value = translateX.value;
+ savedTranslateY.value = translateY.value;
+ startFocalX.value = event.focalX;
+ startFocalY.value = event.focalY;
+ })
+ .onChange((event) => {
scale.value = clampLightboxScale(savedScale.value * event.scale);
+ if (annotating) return;
+ // 画面中心钳制,再补偿回 raw。origin≠0 时不能钳 raw。
+ const next = clampLightboxVisualPan(
+ savedTranslateX.value + (event.focalX - startFocalX.value),
+ savedTranslateY.value + (event.focalY - startFocalY.value),
+ originX.value,
+ originY.value,
+ width,
+ height,
+ scale.value,
+ displayedW.value,
+ displayedH.value,
+ );
+ translateX.value = next.x;
+ translateY.value = next.y;
})
- .onEnd(() => {
- savedScale.value = scale.value;
- if (scale.value <= 1.01) {
- scale.value = withTiming(1);
- savedScale.value = 1;
- translateX.value = withTiming(0);
- translateY.value = withTiming(0);
- savedTranslateX.value = 0;
- savedTranslateY.value = 0;
- runOnJS(setZoomedBoth)(false);
- } else {
- runOnJS(setZoomedBoth)(true);
- }
+ .onFinalize(() => {
+ if (!pinchBusy.value) return;
+ bakePinchOrigin();
+ pinchBusy.value = 0;
+ maybeShowChrome();
});
- // 标注模式下平移改双指专属(单指让给画笔),放大与否都可拖(便于边画边挪视野)。
+ // 浏览:单指平移,未放大时 fail,避免与 pinch 抢 2 指。
+ // 标注:恰好双指平移,1x 也可挪视野。
const panZoomed = Gesture.Pan()
- .enabled(annotating || pageZoomed)
.minPointers(annotating ? 2 : 1)
- .onUpdate((event) => {
- translateX.value = clampLightboxTranslation(savedTranslateX.value + event.translationX, width, scale.value);
- translateY.value = clampLightboxTranslation(savedTranslateY.value + event.translationY, height, scale.value);
+ .maxPointers(annotating ? 2 : 1)
+ .onTouchesDown((_event, state) => {
+ if (!annotating && !isLightboxZoomed(scale.value)) state.fail();
+ })
+ .onStart(() => {
+ panBusy.value = 1;
+ doubleTapBusy.value = 0;
+ hideChrome();
+ savedTranslateX.value = translateX.value;
+ savedTranslateY.value = translateY.value;
+ })
+ .onChange((event) => {
+ // 标注双指 pan 与 off-center pinch Simultaneous,origin 常非 0;
+ // 浏览单指 pan 的 origin 已 bake 归零,helper 退化为钳 raw。
+ const next = clampLightboxVisualPan(
+ translateX.value + event.changeX,
+ translateY.value + event.changeY,
+ originX.value,
+ originY.value,
+ width,
+ height,
+ scale.value,
+ displayedW.value,
+ displayedH.value,
+ );
+ translateX.value = next.x;
+ translateY.value = next.y;
})
- .onEnd(() => {
+ .onFinalize(() => {
savedTranslateX.value = translateX.value;
savedTranslateY.value = translateY.value;
+ if (!panBusy.value) return;
+ panBusy.value = 0;
+ maybeShowChrome();
});
const panDismiss = Gesture.Pan()
- .enabled(!pageZoomed && !annotating)
+ .enabled(!annotating)
+ .maxPointers(1)
+ .onTouchesDown((_event, state) => {
+ if (isLightboxZoomed(scale.value)) state.fail();
+ })
+ .onTouchesMove((_event, state) => {
+ // Simultaneous 下 onTouchesDown 的 fail 经常来不及:放大后竖直滑会被
+ // activeOffsetY 认成下滑关闭。横图 contain 后即使 2.5x 也常无纵向溢出,
+ // 图不动、手还在往下,手势就落到关闭上。
+ if (isLightboxZoomed(scale.value)) state.fail();
+ })
.activeOffsetY([-16, 16])
.failOffsetX([-12, 12])
.onUpdate((event) => {
+ if (isLightboxZoomed(scale.value)) {
+ dragY.value = 0;
+ dismissY.value = 0;
+ return;
+ }
dragY.value = event.translationY;
dismissY.value = event.translationY;
})
.onEnd((event) => {
- if (shouldDismissLightbox(event.translationY, event.velocityY)) {
+ if (shouldDismissLightbox(event.translationY, event.velocityY, scale.value)) {
runOnJS(onRequestClose)();
return;
}
dragY.value = withSpring(0, { damping: 20, stiffness: 240 });
dismissY.value = withSpring(0, { damping: 20, stiffness: 240 });
+ })
+ .onFinalize((_event, success) => {
+ // fail/cancel 不走 onEnd:下滑半途被捏合抢走时,位移和背景渐隐必须立刻清掉。
+ // success 路径由 onEnd 负责(关闭或回弹),这里不要抢。
+ if (success) return;
+ dragY.value = 0;
+ dismissY.value = 0;
});
const doubleTap = Gesture.Tap()
.enabled(!annotating)
.numberOfTaps(2)
- .onEnd((_event, success) => {
+ .onEnd((event, success) => {
if (!success) return;
const next = nextDoubleTapScale(scale.value);
+ originX.value = 0;
+ originY.value = 0;
+ doubleTapBusy.value = 1;
+ const clearDoubleTapBusy = (finished?: boolean) => {
+ 'worklet';
+ if (!finished || !doubleTapBusy.value) return;
+ doubleTapBusy.value = 0;
+ // 尺寸变化只改过 saved:与 scale 同一拍结束时把 live 收到新 contain 边界。
+ translateX.value = savedTranslateX.value;
+ translateY.value = savedTranslateY.value;
+ };
+ if (!isLightboxZoomed(next)) {
+ scale.value = withTiming(1);
+ savedScale.value = 1;
+ translateX.value = withTiming(0);
+ translateY.value = withTiming(0, undefined, clearDoubleTapBusy);
+ savedTranslateX.value = 0;
+ savedTranslateY.value = 0;
+ runOnJS(reportZoomed)(false);
+ return;
+ }
+ const tx = clampLightboxTranslation(
+ lightboxDoubleTapTranslate(event.x, width, next),
+ width,
+ next,
+ displayedW.value,
+ );
+ const ty = clampLightboxTranslation(
+ lightboxDoubleTapTranslate(event.y, height, next),
+ height,
+ next,
+ displayedH.value,
+ );
scale.value = withTiming(next);
savedScale.value = next;
- translateX.value = withTiming(0);
- translateY.value = withTiming(0);
- savedTranslateX.value = 0;
- savedTranslateY.value = 0;
- runOnJS(setZoomedBoth)(next > 1);
+ translateX.value = withTiming(tx);
+ translateY.value = withTiming(ty, undefined, clearDoubleTapBusy);
+ savedTranslateX.value = tx;
+ savedTranslateY.value = ty;
+ runOnJS(reportZoomed)(true);
});
const singleTap = Gesture.Tap()
.enabled(!annotating)
.numberOfTaps(1)
+ .maxDistance(LIGHTBOX_TAP_MAX_DISTANCE)
.onEnd((_event, success) => {
- if (success) runOnJS(onRequestClose)();
+ if (success && shouldCloseLightboxOnTap(scale.value)) runOnJS(onRequestClose)();
});
// 画笔:单指跟手采点(worklet 只搬运坐标 + transform 快照,归一化在 JS 侧
@@ -896,15 +1132,20 @@ const LightboxPage = memo(function LightboxPage({
panDismiss,
panDraw,
);
- // 共享值引用恒定,只有布尔开关与尺寸变化需要重建手势
+ // 共享值引用恒定,只有布尔开关与尺寸变化需要重建手势。不再把 zoomed
+ // 放进 deps:捏合结束改 React 状态会整图重建手势图,正是卡顿来源。
// eslint-disable-next-line react-hooks/exhaustive-deps
- }, [pageZoomed, annotating, width, height, onRequestClose, setZoomedBoth, onDrawPoint]);
+ }, [annotating, width, height, onRequestClose, reportZoomed, onDrawPoint, onChromeBusy]);
const imageStyle = useAnimatedStyle(() => ({
transform: [
{ translateX: translateX.value },
{ translateY: translateY.value + dragY.value },
+ { translateX: originX.value },
+ { translateY: originY.value },
{ scale: scale.value },
+ { translateX: -originX.value },
+ { translateY: -originY.value },
],
}));
diff --git a/apps/mobile/src/session/imageLightboxModel.ts b/apps/mobile/src/session/imageLightboxModel.ts
index 608f13872c..4a7695f163 100644
--- a/apps/mobile/src/session/imageLightboxModel.ts
+++ b/apps/mobile/src/session/imageLightboxModel.ts
@@ -9,9 +9,16 @@ export const LIGHTBOX_MIN_SCALE = 1;
export const LIGHTBOX_MAX_SCALE = 4;
/** 双击放大的目标倍率(IM 惯例 2~3 倍之间)。 */
export const LIGHTBOX_DOUBLE_TAP_SCALE = 2.5;
+/** 视为「已放大」的最小超出量,避免 1.0001 这种浮点噪声锁住翻页。 */
+export const LIGHTBOX_ZOOM_EPS = 0.01;
/** 下滑关闭:位移超过此值(px)或速度超过 velocity 阈值即关闭。 */
export const LIGHTBOX_DISMISS_DISTANCE = 120;
export const LIGHTBOX_DISMISS_VELOCITY = 800;
+/**
+ * 单击关闭允许的最大位移(pt)。RNGH Tap 默认 maxDist 为无限(NAN 跳过校验),
+ * 与平移 Simultaneous 时,500ms 内的短拖松手会被当成单击,lightbox 直接关掉。
+ */
+export const LIGHTBOX_TAP_MAX_DISTANCE = 12;
export function clampLightboxScale(scale: number): number {
'worklet';
@@ -20,29 +27,185 @@ export function clampLightboxScale(scale: number): number {
return scale;
}
+export function isLightboxZoomed(scale: number): boolean {
+ 'worklet';
+ return scale > LIGHTBOX_MIN_SCALE + LIGHTBOX_ZOOM_EPS;
+}
+
/**
- * 放大后的平移钳制:图片(contain 适配后与容器同尺寸的逻辑框)按 scale 放大,
- * 超出容器的部分才允许平移;未超出的轴锁死在 0,防止把图拖出屏幕。
+ * contain 适配后的显示尺寸。自然尺寸未知时退回容器(按铺满估算,宁可少拖一点)。
+ * 与 annotationBaseRect 同源,但不返回 left/top——平移钳制只需要边长。
+ */
+export function lightboxContainedSize(
+ containerWidth: number,
+ containerHeight: number,
+ naturalWidth: number,
+ naturalHeight: number,
+): { width: number; height: number } {
+ 'worklet';
+ if (containerWidth <= 0 || containerHeight <= 0 || naturalWidth <= 0 || naturalHeight <= 0) {
+ return { width: containerWidth, height: containerHeight };
+ }
+ const fit = Math.min(containerWidth / naturalWidth, containerHeight / naturalHeight);
+ return { width: naturalWidth * fit, height: naturalHeight * fit };
+}
+
+/** 某轴允许的平移半幅:放大后的显示边超出容器的一半;未超出则为 0。 */
+export function lightboxPanOverflow(
+ containerSize: number,
+ displayedSize: number,
+ scale: number,
+): number {
+ 'worklet';
+ const size = displayedSize <= 0 ? containerSize : displayedSize;
+ return Math.max(0, (size * scale - containerSize) / 2);
+}
+
+/**
+ * 放大后的平移钳制:图片按 contain 显示后再乘 scale,超出容器的部分才允许平移;
+ * 未超出的轴锁死在 0,防止把图拖出屏幕。displayedSize 缺省时按铺满容器估算
+ * (旧调用点 / 自然尺寸未到)。
*/
export function clampLightboxTranslation(
value: number,
containerSize: number,
scale: number,
+ displayedSize?: number,
): number {
'worklet';
- const overflow = Math.max(0, (containerSize * scale - containerSize) / 2);
+ const overflow = lightboxPanOverflow(
+ containerSize,
+ displayedSize == null ? containerSize : displayedSize,
+ scale,
+ );
if (value < -overflow) return -overflow;
if (value > overflow) return overflow;
return value;
}
-/** 下滑手势释放时是否应关闭(距离或甩动速度任一超阈值)。 */
-export function shouldDismissLightbox(translationY: number, velocityY: number): boolean {
+/**
+ * 显示尺寸变化后(自然尺寸到达 / 旋转)按新 contain 边界重钳位移。
+ * 未知尺寸按铺满容器估算,横图 onLoad 后高变小,旧位移必须立刻收回,
+ * 不能等下次拖动手才跳回边界。
+ */
+export function reclampLightboxPan(
+ translateX: number,
+ translateY: number,
+ containerWidth: number,
+ containerHeight: number,
+ scale: number,
+ displayedWidth: number,
+ displayedHeight: number,
+): { x: number; y: number } {
+ 'worklet';
+ return {
+ x: clampLightboxTranslation(translateX, containerWidth, scale, displayedWidth),
+ y: clampLightboxTranslation(translateY, containerHeight, scale, displayedHeight),
+ };
+}
+
+/** 捏合焦点相对容器中心,作为 scale 的 transform origin。 */
+export function lightboxPinchOrigin(focal: number, containerSize: number): number {
+ 'worklet';
+ return focal - containerSize / 2;
+}
+
+/**
+ * 把 origin 缩放折进 translation,之后 origin 可归零而不跳变。
+ * p' = (p - origin) * scale + origin + translate
+ * = p * scale + origin * (1 - scale) + translate
+ */
+export function bakeLightboxOrigin(translate: number, origin: number, scale: number): number {
+ 'worklet';
+ return translate + origin * (1 - scale);
+}
+
+/**
+ * bake 的逆运算:已有缩放时再设 origin,从 translate 扣掉 origin*(1-scale),
+ * 画面公式不变。二次捏合若不补偿,imageStyle 会立刻加上 origin*(1-scale) 跳一下,
+ * 结束时 bake 还会把这次跳变写进位移。
+ */
+export function compensateLightboxOrigin(translate: number, origin: number, scale: number): number {
+ 'worklet';
+ return translate - origin * (1 - scale);
+}
+
+/**
+ * 画面中心(bake 后)钳进 contain 边界,再补偿回带 origin 的 raw translate。
+ * origin≠0 时钳 raw 会让画面越出边界,松手 bake 再弹回。origin=0 时 bake/补偿
+ * 是恒等,与直接钳 translate 相同——浏览捏合与标注双指平移共用这一条。
+ */
+export function clampLightboxVisualPan(
+ translateX: number,
+ translateY: number,
+ originX: number,
+ originY: number,
+ containerWidth: number,
+ containerHeight: number,
+ scale: number,
+ displayedWidth: number,
+ displayedHeight: number,
+): { x: number; y: number } {
'worklet';
+ return {
+ x: compensateLightboxOrigin(
+ clampLightboxTranslation(
+ bakeLightboxOrigin(translateX, originX, scale),
+ containerWidth,
+ scale,
+ displayedWidth,
+ ),
+ originX,
+ scale,
+ ),
+ y: compensateLightboxOrigin(
+ clampLightboxTranslation(
+ bakeLightboxOrigin(translateY, originY, scale),
+ containerHeight,
+ scale,
+ displayedHeight,
+ ),
+ originY,
+ scale,
+ ),
+ };
+}
+
+/**
+ * 双击目标平移:点击点在缩放到 targetScale 后仍停在原处;缩回 1x 时归零。
+ */
+export function lightboxDoubleTapTranslate(
+ tap: number,
+ containerSize: number,
+ targetScale: number,
+): number {
+ 'worklet';
+ if (!isLightboxZoomed(targetScale)) return 0;
+ return lightboxPinchOrigin(tap, containerSize) * (1 - targetScale);
+}
+
+/**
+ * 下滑手势释放时是否应关闭(距离或甩动速度任一超阈值)。
+ * 放大后一律不关:contain 横图即使 2.5x 也常无纵向溢出,同一记向下滑会被 Simultaneous
+ * 的关闭手势当成 dismiss;scale 必须参与判定,不能只靠手势 fail()。
+ */
+export function shouldDismissLightbox(
+ translationY: number,
+ velocityY: number,
+ scale: number = LIGHTBOX_MIN_SCALE,
+): boolean {
+ 'worklet';
+ if (isLightboxZoomed(scale)) return false;
return Math.abs(translationY) > LIGHTBOX_DISMISS_DISTANCE
|| Math.abs(velocityY) > LIGHTBOX_DISMISS_VELOCITY;
}
+/** 单击是否关闭:仅 1x。放大时单击留给看图,避免和拖图/双击抢手势。 */
+export function shouldCloseLightboxOnTap(scale: number): boolean {
+ 'worklet';
+ return !isLightboxZoomed(scale);
+}
+
/** 下滑拖动中的背景不透明度:拖过半屏降到 0.3,跟手渐隐。 */
export function lightboxBackgroundOpacity(translationY: number, containerHeight: number): number {
'worklet';
@@ -54,7 +217,7 @@ export function lightboxBackgroundOpacity(translationY: number, containerHeight:
/** 双击在 1x 与放大倍率间切换。 */
export function nextDoubleTapScale(currentScale: number): number {
'worklet';
- return currentScale > LIGHTBOX_MIN_SCALE + 0.01 ? LIGHTBOX_MIN_SCALE : LIGHTBOX_DOUBLE_TAP_SCALE;
+ return isLightboxZoomed(currentScale) ? LIGHTBOX_MIN_SCALE : LIGHTBOX_DOUBLE_TAP_SCALE;
}
/** 横向分页偏移 → 页索引(pagingEnabled 的 momentum end)。 */