Consider it done. The open-source AI agent that works out of the box · 想到,就能做到。开源、开箱即用的 AI Agent。
TypeScript agentai-agentai-assistantandroidclaude-codecodexelectroniosllmmacosreact-nativetypescriptwindows
/**
* ImageLightbox — IM 级全屏图片查看器。
* ---------------------------------------------------------------------------
* 点缩略图直接全屏黑底看图,交互对齐主流 IM:
* - 双指捏合绕焦点缩放(1x~4x,可捏过两端再弹回);放大后单指平移,
* 越过图片边界有橡皮筋阻尼,松手带惯性滑行、越界弹回(对齐系统相册)
* - 双击在 1x / 2.5x 间切换并落到点击点;单击隐藏 / 显示 chrome(不关闭)
* - 1x 下竖直下滑跟手关闭(位移 + 背景渐隐),横滑翻同一条消息里的图片 / 视频
* - 原图还在取件 / 下载时,垫底的缩略图同样可缩放、单击,工具栏照常显示
* (未就绪的操作置灰),不必等加载完
* - 捏合/平移期间 chrome 让位(不抢触摸),结束后恢复
* - chrome 极简:顶部关闭与多图页码,底部标注/发送/分享;关闭同时支持读屏返回
* 手势判定全部走 imageLightboxModel.ts 纯函数;取件复用会话屏的队列 + 磁盘缓存
* (onResolveRemoteMedia),点开时通常已被列表缩略图取过、秒出。
* 视频页用系统原生播放器(无缩放手势,chrome 常驻);音频 / 文件仍走 MessagePayloadModal。
* lightbox 是常黑沉浸语境,黑白系颜色为刻意豁免(对齐桌面 docs/design-rules/cindy-design-system.md overlay/lightbox 语义豁免),不走主题 token。
*/
import { useNavigation } from 'expo-router';
import { Image } from 'expo-image';
import { memo, useCallback, useEffect, useLayoutEffect, useMemo, useRef, useState } from 'react';
import { useTranslation } from 'react-i18next';
import {
ActivityIndicator,
Alert,
FlatList,
Modal,
Platform,
Pressable,
StatusBar,
StyleSheet,
useWindowDimensions,
View,
} from 'react-native';
import { Text } from '@/components/AppText';
import { ErrorNotice, ErrorNoticeAction } from '@/components/ErrorNotice';
import { MessageSquarePlus, Pen, Share as ShareIcon, Undo2, X } from 'lucide-react-native';
import Svg, { Path } from 'react-native-svg';
import { fontWeight, iconSize, iconStroke, lineHeight, motionDuration, radius, typeScale } from '@/theme';
import { Gesture, GestureDetector, GestureHandlerRootView } from '@/platform/gestureHandler';
import Animated, {
cancelAnimation,
runOnJS,
useAnimatedStyle,
useSharedValue,
withDecay,
withSpring,
withTiming,
type SharedValue,
} from 'react-native-reanimated';
import { useSafeAreaInsets } from 'react-native-safe-area-context';
import type { MobileMessageGalleryImage } from '@/session/messageGallery';
import { RemoteMediaPlayerWebView } from '@/session/mediaPlayerWebView';
import type { MobileMediaPlayerStatus } from '@/session/mediaPlayerWebViewHtml';
import { NativeVideoPlayer } from '@/session/NativeVideoPlayer';
import {
isDesktopLocalMediaUrl,
mediaLoadFailureKey,
type MobileResolvedRemoteMedia,
type ResolveRemoteMediaFn,
} from '@/session/remoteMedia';
import {
bakeLightboxOrigin,
canShareLightboxImage,
compensateLightboxOrigin,
clampLightboxTranslation,
dragLightboxVisualPan,
isLightboxZoomed,
lightboxBackgroundOpacity,
lightboxContainedSize,
lightboxDoubleTapTranslate,
lightboxImageLayers,
lightboxInitialIndex,
lightboxPageIndex,
lightboxPageLabel,
lightboxPanRelease,
lightboxPinchAnchor,
lightboxPinchOrigin,
lightboxPinchSettle,
lightboxPinchTranslation,
LIGHTBOX_MAX_SCALE,
LIGHTBOX_MIN_SCALE,
LIGHTBOX_TAP_MAX_DISTANCE,
nextDoubleTapScale,
reclampLightboxPan,
rubberBandLightboxScale,
shouldDismissLightbox,
unrubberLightboxScale,
} from '@/session/imageLightboxModel';
import {
ANNOTATION_OUTLINE_COLOR,
ANNOTATION_STROKE_COLOR,
annotationBaseRect,
annotationDisplayRect,
annotationMinPointDistanceForRect,
annotationOutlineWidth,
annotationStrokesEqual,
annotationStrokeToSvgPath,
annotationStrokeWidth,
canAnnotateImageMime,
normalizeAnnotationPoint,
shouldAppendAnnotationPoint,
shouldDiscardInterruptedStroke,
type AnnotationStroke,
} from '@/session/imageAnnotationModel';
// Use the existing SVG-capable decoder for both the preview and full image,
// retaining the lightbox's native gesture transforms.
const AnimatedImage = Animated.createAnimatedComponent(Image);
/** 越界 / 捏过两端松手的回弹:接近临界阻尼,约 0.3s 落定,几乎不来回晃。 */
const LIGHTBOX_SETTLE_SPRING = { damping: 30, stiffness: 260, mass: 1 } as const;
// 缩略图垫底**不**挂在取件态里:它要跨过 loading → ready 的边界继续垫住原图
// 下载那一段(见 lightboxImageLayers),挂进 loading 分支会在取件完成的瞬间
// 结构性丢失,把第二段空档裸露成纯黑。垫底地址单独存 previewMap。
type PageResolveState =
| { status: 'loading'; media?: MobileResolvedRemoteMedia }
| { status: 'ready'; media: MobileResolvedRemoteMedia }
| { status: 'error'; error?: unknown; media?: MobileResolvedRemoteMedia };
/** 宿主注入的底部操作(文件浏览器:复制路径/发送到会话);回调收当前活跃页。 */
export interface ImageLightboxAction {
key: string;
label: string;
icon: React.ComponentType<{ color?: string; size?: number; strokeWidth?: number }>;
onPress: (image: MobileMessageGalleryImage) => void;
}
/**
* 圈点标注配置(可选)。提供时,可标注的页(位图 + 已有本地/直连字节)右下角
* 出现画笔圆钮:进入标注模式后单指作画(红笔 + 白描边,与桌面版同视觉)、
* 双指仍可缩放平移、可撤销;提交出口由宿主决定语义(聊天=发送到对话,
* composer 托盘=保存替换附件)。烧录发生在宿主侧(onSubmit 之后),lightbox
* 只产出矢量笔迹。
*/
export interface ImageLightboxAnnotationConfig {
/** 提交文案(如「发送到对话」/「保存」)。 */
submitLabel: string;
/**
* 非标注态是否显示独立的直发按钮(文案同 submitLabel,提交空笔迹 = 转发
* 原图)。聊天场景 true(对齐桌面的一级「发送到对话」);composer 托盘场景
* 不开(图已在托盘,直发无意义)。gif 等不可标注的图也能直发。
*/
allowDirectSubmit?: boolean;
/**
* 提交:strokes 为当前全部笔迹(可为空,空的语义由宿主定——聊天=转发原图,
* 托盘再编辑=撤光恢复原图)。resolve 后 lightbox 关闭;reject 时停留在标注
* 模式(宿主自行提示错误)。
*/
onSubmit: (
image: MobileMessageGalleryImage,
displayUri: string,
strokes: AnnotationStroke[],
/** naturalWidth / naturalHeight:查看器已解码的图片尺寸(未加载完成时缺省)。 */
context: { mimeType?: string; naturalWidth?: number; naturalHeight?: number },
) => void | Promise<void>;
/**
* 某页的既有笔迹(托盘带标注图再编辑):打开/翻页时叠加显示,进入标注模式
* 可继续画或撤销。不提供 = 全部从空白开始。
*/
initialStrokesFor?: (image: MobileMessageGalleryImage) => readonly AnnotationStroke[] | undefined;
/**
* 某页此刻暂不能进入标注的原因(可选;返回 undefined = 可以)。有原因时画笔
* 按钮置灰但仍可点,点按弹出该说明(如托盘附件的上一次修改尚未上传完成)。
*/
annotationBlockedReason?: (image: MobileMessageGalleryImage) => string | undefined;
/**
* 进入标注模式时调用(可选):宿主据此提前准备提交所需资源(烧录 WebView
* 预热)。返回的释放函数在退出标注 / 关闭查看器时调用。
*/
prewarm?: () => () => void;
}
export interface ImageLightboxProps {
images: readonly MobileMessageGalleryImage[];
initialUrl: string;
/** Same-content attachment slots can share a URL; prefer the clicked attachment's identity. */
initialImageKey?: string;
onClose(): void;
onResolveRemoteMedia?: ResolveRemoteMediaFn;
/** 关闭时逐出本次取过的视频(与通用查看器一致;图片缩略图常驻列表不逐出)。 */
onReleaseRemoteMedia?: (sourceUrl: string, media: MobileResolvedRemoteMedia) => void;
/** 分享当前图(displayUri 为 file:// 或 http(s));由会话屏落地本地文件后唤起系统分享单。 */
onShareImage?: (
media: MobileMessageGalleryImage['payload']['media'],
displayUri: string,
mimeType?: string,
/** 取件已知的对象字节数:分享落盘可据此跳过超预算的 LRU 写入。 */
sizeBytes?: number,
) => void | Promise<void>;
/**
* 额外底部操作(可选)。提供时底部渲染成图标+文字工具栏(与文件预览页
* 底栏同构,操作显式可见);不提供维持聊天原样(仅右下分享圆钮)。
* 聊天调用方不传,此 prop 对聊天零影响。
*/
extraActions?: readonly ImageLightboxAction[];
/**
* 文件预览顶栏(可选):完成 + 文件名/meta + 分享,与 Quick Look 预览页
* 同构(深色沉浸变体)。开启时分享上移到顶栏,底部只剩 extraActions;
* 顶部页码并入 meta 行。聊天调用方不传,维持无顶栏的极简 chrome。
*/
showFileHeader?: boolean;
/** 圈点标注(可选):见 {@link ImageLightboxAnnotationConfig}。 */
annotation?: ImageLightboxAnnotationConfig;
/**
* 打开即进入标注模式(需同时提供 annotation;对齐桌面 autoAnnotate)。
* 为标注而开的临时图(如图表导出)用:放弃标注(取消 / 返回)直接关闭查看器。
*/
autoAnnotate?: boolean;
}
// memo:父层(消息列表)在流式回复期间每 token 重渲染,props 全部引用稳定
// (images 已在父层做语义比对复用、回调均为 useCallback),查看器打开期间整棵
// 子树对流式更新免疫(rule 7)。
export const ImageLightbox = memo(function ImageLightbox({
images,
initialUrl,
initialImageKey,
onClose,
onResolveRemoteMedia,
onReleaseRemoteMedia,
onShareImage,
extraActions,
showFileHeader,
annotation,
autoAnnotate = false,
}: ImageLightboxProps) {
const { t } = useTranslation();
const { width, height } = useWindowDimensions();
const insets = useSafeAreaInsets();
const urls = useMemo(() => images.map((image) => image.url), [images]);
const initialKeyIndex = initialImageKey ? images.findIndex((image) => image.key === initialImageKey) : -1;
const initialIndex = initialKeyIndex >= 0 ? initialKeyIndex : lightboxInitialIndex(urls, initialUrl);
const [activePage, setActivePage] = useState(() => {
const image = images[initialIndex];
return { key: image?.key, url: image?.url, galleryImageKey: image?.payload.galleryImageKey,
galleryImageSlot: image?.payload.galleryImageSlot, index: initialIndex };
});
// 地址升级或相邻附件就绪时,页码跟随图片身份,不跟随旧数组下标。
// 普通消息在流式工作组收尾时会换 key,仍按原地址找回;删除当前页才钳制下标。
const keyIndex = images.findIndex((image) => image.key === activePage.key);
// Replacement and earlier uploads can settle in one render. Preserve the thumbnail slot,
// not the old readable-page index, when the active attachment identity disappears.
const slotIndex = keyIndex < 0 && activePage.galleryImageKey && activePage.galleryImageSlot !== undefined
? images.findIndex((image) => image.payload.galleryImageSlot === activePage.galleryImageSlot) : -1;
// Stable attachment keys distinguish duplicate URLs. A missing key means replacement/removal;
// URL fallback is only for ordinary message pages whose render keys can be rebuilt.
const urlIndex = keyIndex < 0 && !activePage.galleryImageKey
? images.findIndex((image) => image.url === activePage.url) : -1;
const activeIndex = keyIndex >= 0 ? keyIndex : slotIndex >= 0 ? slotIndex : urlIndex >= 0 ? urlIndex
: Math.max(0, Math.min(activePage.index, images.length - 1));
const activePageKey = images[activeIndex]?.key;
const activePageUrl = images[activeIndex]?.url;
const activeGalleryImageKey = images[activeIndex]?.payload.galleryImageKey;
const activeGalleryImageSlot = images[activeIndex]?.payload.galleryImageSlot;
// 记住这次实际显示的身份与位置;换图或钳制后,后续更新继续跟随新图,不能找回旧图。
useLayoutEffect(() => {
if (activePageKey === undefined || activePageUrl === undefined) return;
setActivePage((previous) => previous.key === activePageKey
&& previous.url === activePageUrl && previous.index === activeIndex
&& previous.galleryImageKey === activeGalleryImageKey
&& previous.galleryImageSlot === activeGalleryImageSlot
? previous
: { key: activePageKey, url: activePageUrl, galleryImageKey: activeGalleryImageKey,
galleryImageSlot: activeGalleryImageSlot, index: activeIndex });
}, [activePageKey, activePageUrl, activeGalleryImageKey, activeGalleryImageSlot, activeIndex]);
const [zoomed, setZoomed] = useState(false);
/** 捏合/平移进行中 chrome 不接收触摸,避免底栏抢走双指。 */
const [chromeInteractive, setChromeInteractive] = useState(true);
const [resolveMap, setResolveMap] = useState<Record<string, PageResolveState>>({});
// 跟随逻辑图片身份:上传地址转成正式消息地址时,已解码的同图仍可继续操作。
const [loadedImageKeys, setLoadedImageKeys] = useState<ReadonlySet<string>>(new Set());
/**
* trimmed url → 列表缩略图地址(渐进出图的垫底层)。独立于 resolveMap:
* 一旦拿到就长期有效,取件态怎么流转都不丢,直到原图 onLoad 才停止使用。
*/
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);
}, []);
/** 用户单击切换的 chrome 显隐(与手势期间的临时让位独立)。 */
const [chromeToggledVisible, setChromeToggledVisible] = useState(true);
const toggleChrome = useCallback(() => {
setChromeToggledVisible((visible) => !visible);
}, []);
// ---- 圈点标注状态(仅活跃页;笔迹归一化存储,显示/烧录共用同一映射)----
// autoAnnotate 只作初值:打开即进标注(对齐桌面)。
const autoAnnotateActive = autoAnnotate && !!annotation;
const [isAnnotating, setIsAnnotating] = useState(autoAnnotateActive);
const [annotationSubmitting, setAnnotationSubmitting] = useState(false);
const submittingRef = useRef(false);
const sharingRef = useRef(false);
const [sharing, setSharing] = useState(false);
const onCloseRef = useRef(onClose);
onCloseRef.current = onClose;
useEffect(() => {
if (images.length === 0) onCloseRef.current();
}, [images.length]);
const [strokes, setStrokes] = useState<AnnotationStroke[]>([]);
// 取消 / 返回回调经 ref 读最新笔迹与文案:它们进入手势 deps(onRequestClose),
// 不能因每次作画 / 父层重渲染而让整张手势图重建。
const strokesRef = useRef(strokes);
strokesRef.current = strokes;
const tRef = useRef(t);
tRef.current = t;
const [draftStroke, setDraftStroke] = useState<AnnotationStroke | null>(null);
/** url → 图片自然尺寸(LightboxPage onLoad 上报;overlay 与坐标换算的基准)。 */
const [naturalSizes, setNaturalSizes] = useState<Record<string, { width: number; height: number }>>({});
const draftStrokeRef = useRef<AnnotationStroke | null>(null);
/** 进行中一笔的屏幕路径长度(容器坐标,px)与上一个原始触点:判定捏合误触。 */
const draftScreenLengthRef = useRef(0);
const draftLastScreenPointRef = useRef<{ x: number; y: number } | null>(null);
const discardConfirmOpenRef = useRef(false);
const activeImageForDraw = images[activeIndex] ?? null;
const activeNaturalSize = activeImageForDraw ? naturalSizes[activeImageForDraw.key] ?? null : null;
const handleNaturalSize = useCallback((imageKey: string, size: { width: number; height: number }) => {
setNaturalSizes((prev) => {
const existing = prev[imageKey];
if (existing && existing.width === size.width && existing.height === size.height) return prev;
return { ...prev, [imageKey]: size };
});
}, []);
// 打开/换图时装载该图既有笔迹(托盘再编辑),标注模式中禁用手动翻页。
// 只依赖「活跃图 key」,不依赖数组引用或页码:附件就绪可能让同一张图前移/后移,
// 不能因此重置已画笔迹或正在画的一笔;
// 真正换图(翻页 / 打开另一张)时 key 变化,照常重载。images 经 ref 读最新。
const activeImageKeyForStrokes = images[activeIndex]?.key ?? null;
const imagesRef = useRef(images);
imagesRef.current = images;
useEffect(() => {
const image = imagesRef.current.find((entry) => entry.key === activeImageKeyForStrokes);
const initial = image ? annotation?.initialStrokesFor?.(image) : undefined;
setStrokes(initial ? [...initial] : []);
draftStrokeRef.current = null;
draftLastScreenPointRef.current = null;
draftScreenLengthRef.current = 0;
setDraftStroke(null);
// annotation 语义上只在打开时取一次快照,翻页时按新页(key)重取
// eslint-disable-next-line react-hooks/exhaustive-deps
}, [activeImageKeyForStrokes]);
/**
* 画笔落点(容器坐标 + 当页 transform 状态,LightboxPage 手势经 runOnJS 上抛)。
* end 带手势是否正常结束:第二根手指落下会让单指画笔手势被取消,此时屏幕
* 路径很短的半笔是捏合起手的误触(点 / 小短线),丢弃;点按与真正的笔画照常落笔。
*/
const handleDrawPoint = useCallback((
phase: 'start' | 'move' | 'end',
pointX: number,
pointY: number,
translateX: number,
translateY: number,
scale: number,
gestureSucceeded = true,
) => {
if (submittingRef.current) return;
if (phase === 'end') {
const draft = draftStrokeRef.current;
const screenLength = draftScreenLengthRef.current;
draftStrokeRef.current = null;
draftLastScreenPointRef.current = null;
draftScreenLengthRef.current = 0;
setDraftStroke(null);
if (draft && draft.points.length > 0 && !shouldDiscardInterruptedStroke(gestureSucceeded, screenLength)) {
setStrokes((prev) => [...prev, draft]);
}
return;
}
if (!activeNaturalSize) return;
const base = annotationBaseRect(width, height, activeNaturalSize.width, activeNaturalSize.height);
if (!base) return;
const rect = annotationDisplayRect(base, width, height, translateX, translateY, scale);
const point = normalizeAnnotationPoint(pointX, pointY, rect);
if (!point) return;
if (phase === 'start') {
draftStrokeRef.current = { points: [point] };
draftLastScreenPointRef.current = { x: pointX, y: pointY };
draftScreenLengthRef.current = 0;
setDraftStroke(draftStrokeRef.current);
return;
}
const draft = draftStrokeRef.current;
if (!draft) return;
const lastScreen = draftLastScreenPointRef.current;
if (lastScreen) draftScreenLengthRef.current += Math.hypot(pointX - lastScreen.x, pointY - lastScreen.y);
draftLastScreenPointRef.current = { x: pointX, y: pointY };
// 最小点距按屏幕像素换算:放大作画保精度,1x 不逐事件记录。
if (!shouldAppendAnnotationPoint(draft, point, annotationMinPointDistanceForRect(rect))) return;
// 原地追加(O(1)),只换外层引用触发重渲染;落笔 / 提交后草稿引用即被置空,
// 已提交的笔迹不会再被改动。
draft.points.push(point);
draftStrokeRef.current = { points: draft.points };
setDraftStroke(draftStrokeRef.current);
}, [activeNaturalSize, width, height]);
const undoLastStroke = useCallback(() => {
setStrokes((prev) => prev.slice(0, -1));
draftStrokeRef.current = null;
draftLastScreenPointRef.current = null;
draftScreenLengthRef.current = 0;
setDraftStroke(null);
}, []);
/**
* 放弃标注:恢复到该页既有笔迹并退出标注模式。autoAnnotate 宿主(为标注而开
* 的临时图)留在查看器没有意义,直接关闭(对齐桌面)。
*/
const discardAnnotation = useCallback(() => {
if (autoAnnotateActive) {
onCloseRef.current();
return;
}
const image = images[activeIndex];
const initial = image ? annotation?.initialStrokesFor?.(image) : undefined;
setStrokes(initial ? [...initial] : []);
draftStrokeRef.current = null;
draftLastScreenPointRef.current = null;
draftScreenLengthRef.current = 0;
setDraftStroke(null);
setIsAnnotating(false);
}, [activeIndex, images, annotation, autoAnnotateActive]);
/**
* 取消 / 返回:笔迹与打开时一致则直接放弃(与以往完全相同);有未保存的改动
* 先确认,避免误触丢掉整张图的圈点。
*/
const exitAnnotationMode = useCallback(() => {
if (submittingRef.current) return;
const image = images[activeIndex];
const baseline = (image ? annotation?.initialStrokesFor?.(image) : undefined) ?? EMPTY_STROKES;
const changed = !!draftStrokeRef.current?.points.length
|| !annotationStrokesEqual(strokesRef.current, baseline);
if (!changed) {
discardAnnotation();
return;
}
if (discardConfirmOpenRef.current) return;
discardConfirmOpenRef.current = true;
const settle = () => { discardConfirmOpenRef.current = false; };
const t = tRef.current;
Alert.alert(
t('message.lightbox.discardAnnotationTitle'),
t('message.lightbox.discardAnnotationBody'),
[
{ text: t('message.lightbox.continueAnnotating'), style: 'cancel', onPress: settle },
{
text: t('message.lightbox.discardAnnotation'),
style: 'destructive',
onPress: () => {
settle();
discardAnnotation();
},
},
],
{ cancelable: true, onDismiss: settle },
);
}, [activeIndex, images, annotation, discardAnnotation]);
// 标注模式期间让宿主预热提交资源(烧录 WebView);退出 / 关闭时释放。
const prewarmAnnotation = annotation?.prewarm;
useEffect(() => {
if (!isAnnotating || !prewarmAnnotation) return undefined;
return prewarmAnnotation();
}, [isAnnotating, prewarmAnnotation]);
// 每 url 只自动强制重取一次(Image 加载失败自愈),防 onError↔重取死循环;
// 重试按钮的显式 forceRefresh 不受此限制。
const imageErrorRetryUsedRef = useRef<Set<string>>(new Set());
const resolvingImagesRef = useRef(new Set<string>());
const resolveMapRef = useRef(resolveMap);
resolveMapRef.current = resolveMap;
const listRef = useRef<FlatList<MobileMessageGalleryImage>>(null);
// 旋转或图集变动导致页码变化时重锚,保持画面、页码和分享目标一致。
useEffect(() => {
listRef.current?.scrollToOffset({ animated: false, offset: activeIndex * width });
}, [activeIndex, width]);
const resolveImage = useCallback((
image: MobileMessageGalleryImage,
front: boolean,
forceRefresh = false,
) => {
if (!onResolveRemoteMedia) return;
const media = image.payload.media;
if (media.previewable || !isDesktopLocalMediaUrl(media.url)) return;
// resolveMap 一律以 gallery 的 trimmed url(image.url)为键:media.url 未 trim,
// 带空白时会和 renderItem / handleShare 的查键错位。取件请求仍传原始 media.url,
// 与缩略图路径的队列缓存键保持一致(不产生重复上传)。
const key = image.url;
const current = resolveMapRef.current[key];
if (resolvingImagesRef.current.has(key)) {
if (front && !forceRefresh) {
// 翻到预取页时仍须提升已有取件;cachedOnly 保证不会新建下载,
// 不带队列的文件浏览解析器也只读缓存。结果仍由首次请求回填。
void onResolveRemoteMedia(
{ kind: media.kind, url: media.url, previewable: media.previewable },
{ front: true, cachedOnly: true },
).catch(() => undefined);
}
return;
}
if (!forceRefresh && current && current.status !== 'error') return;
resolvingImagesRef.current.add(key);
setResolveMap((prev) => {
// 显示副本与取件状态分开:刷新失败不撤掉仍可读的原图,也不假装刷新成功。
return { ...prev, [key]: { status: 'loading', media: prev[key]?.media } };
});
void onResolveRemoteMedia(
{ kind: media.kind, url: media.url, previewable: media.previewable },
{ front, forceRefresh },
)
.then((resolved) => {
setResolveMap((prev) => ({ ...prev, [key]: { status: 'ready', media: resolved } }));
})
.catch((error: unknown) => {
setResolveMap((prev) => ({ ...prev, [key]: { status: 'error', error, media: prev[key]?.media } }));
})
.finally(() => resolvingImagesRef.current.delete(key));
// 垫底缩略图:列表里这张图已经解码好了,拿来从打开那一刻接住画面,一直垫到
// 原图 onLoad(见 lightboxImageLayers)。写入**不看取件态** —— 原图可能在同
// 一批微任务里就从内存/磁盘缓存返回,旧实现要求"当前必须是 loading"才写垫底,
// 这条竞态下垫底被直接丢弃,画面又退回纯黑。
// cachedOnly:只复用列表已取过的缩略图缓存,绝不触发新取件——对 gif/老被控端,
// thumbnail 请求会回落成整张原图下载,装饰性垫底叠加原图主取件就是双下载。
// forceRefresh 是坏对象自愈路径,不垫可能同源的旧缩略图;取不到缩略图退回
// spinner(lightboxImageLayers 兜底),不影响原图路径。
if (!forceRefresh) {
void onResolveRemoteMedia(
{ kind: media.kind, url: media.url, previewable: media.previewable, thumbnail: true },
{ front: false, cachedOnly: true },
)
.then((thumb) => {
if (!thumb.previewable || !thumb.url) return;
setPreviewMap((prev) => (prev[key] ? prev : { ...prev, [key]: thumb.url }));
})
.catch(() => undefined);
}
// 在途请求按图片合并;error 态由重试按钮显式再调。
}, [onResolveRemoteMedia]);
// 重试按钮:显式 forceRefresh 穿透负缓存。稳定引用(带 image 参数)让
// LightboxPage 的 memo 在父层重渲染时不被内联闭包击穿。
const handleRetryPage = useCallback((image: MobileMessageGalleryImage) => {
resolveImage(image, true, true);
}, [resolveImage]);
// 取件成功但原生 Image 加载失败(典型:桌面去重缓存返回了已被删除的悬空 key,
// presign 下载 404)→ 一次性 forceRefresh 重取自愈,再失败落错误态给重试按钮。
const handleImageLoadError = useCallback((image: MobileMessageGalleryImage) => {
const key = image.url; // resolveMap / 重试集统一用 trimmed gallery 键
setLoadedImageKeys((prev) => {
if (!prev.has(image.key)) return prev;
const next = new Set(prev);
next.delete(image.key);
return next;
});
if (imageErrorRetryUsedRef.current.has(key)) {
setResolveMap((prev) => ({ ...prev, [key]: { status: 'error' } }));
return;
}
imageErrorRetryUsedRef.current.add(key);
resolveImage(image, true, true);
}, [resolveImage]);
const handleImageLoaded = useCallback((image: MobileMessageGalleryImage, media?: MobileResolvedRemoteMedia) => {
if (media && resolveMapRef.current[image.url]?.media !== media) return;
if (!media && !image.payload.media.previewable) return;
setLoadedImageKeys((prev) => prev.has(image.key) ? prev : new Set(prev).add(image.key));
}, []);
// 活跃页插队取件,相邻图片页顺队预取(翻页即无缝)。视频体积大,只在翻到
// 它时才取,不为「可能会看」预先整段搬运。
useEffect(() => {
const active = images[activeIndex];
if (active) resolveImage(active, true);
const prev = images[activeIndex - 1];
if (prev && prev.payload.media.kind === 'image') resolveImage(prev, false);
const next = images[activeIndex + 1];
if (next && next.payload.media.kind === 'image') resolveImage(next, false);
}, [activeIndex, images, resolveImage]);
// 关闭时逐出本次取过的视频(与通用查看器同一口径:只逐出 JS 缓存,
// 远端对象由会话页统一回收);图片缩略图常驻列表,不逐出。
const onReleaseRemoteMediaRef = useRef(onReleaseRemoteMedia);
onReleaseRemoteMediaRef.current = onReleaseRemoteMedia;
useEffect(() => () => {
const release = onReleaseRemoteMediaRef.current;
if (!release) return;
for (const image of imagesRef.current) {
const state = resolveMapRef.current[image.url];
if (image.payload.media.kind === 'video' && state?.media) {
release(image.payload.media.url, state.media);
}
}
}, []);
const displayUriFor = useCallback((image: MobileMessageGalleryImage): string | null => {
const media = image.payload.media;
if (media.previewable && media.url) return media.url;
const state = resolveMap[image.url];
if (state?.media?.previewable) return state.media.url;
return null;
}, [resolveMap]);
/**
* 该页的垫底缩略图。手机本地已有的同图(自己发出的图)优先:同步可用,打开第一帧
* 就有画面;其次是列表已取过的远程缩略图。与原图地址相同时返回 null:磁盘缓存
* 命中会让缩略图与原图落到同一个 file://(缩不动的图按裸键落盘),此时垫同一张图
* 纯属多解码一份,且原图本就秒出。
*/
const previewUriFor = useCallback((image: MobileMessageGalleryImage): string | null => {
const preview = image.previewUri ?? previewMap[image.url];
if (!preview) return null;
return preview === displayUriFor(image) ? null : preview;
}, [previewMap, displayUriFor]);
const backdropStyle = useAnimatedStyle(() => ({
opacity: lightboxBackgroundOpacity(dismissY.value, height),
}));
const activeImage = images[activeIndex] ?? null;
const activeIsVideo = activeImage?.payload.media.kind === 'video';
// 视频页没有单击切换(单击交给系统播放控件),标注态的操作栏不能藏:两者 chrome 常驻。
const chromeShown = chromeToggledVisible || isAnnotating || activeIsVideo;
const chromeToggleHidden = useSharedValue(0);
useEffect(() => {
chromeToggleHidden.value = withTiming(chromeShown ? 0 : 1, { duration: motionDuration.fast });
// 共享值引用恒定
// eslint-disable-next-line react-hooks/exhaustive-deps
}, [chromeShown]);
const chromeStyle = useAnimatedStyle(() => ({
opacity: lightboxBackgroundOpacity(dismissY.value, height)
* (1 - chromeHidden.value)
* (1 - chromeToggleHidden.value),
}));
const activeUri = activeImage ? displayUriFor(activeImage) : null;
const activeResolveState = activeImage ? resolveMap[activeImage.url] : undefined;
// Expo can display library handles, but sharing/annotation need the file or remote
// original supplied later by the existing upload pipeline. Do not enable dead-end actions.
const activeActionsReady = !!activeUri && !/^(?:ph|content|assets-library):\/\//.test(activeUri)
&& (activeImage?.payload.media.previewable
|| (activeResolveState?.status === 'ready' && !!activeImage && loadedImageKeys.has(activeImage.key)));
const pageLabel = lightboxPageLabel(activeIndex, images.length);
// 工具栏从打开那一刻就在:原图还在取件时先置灰,就绪即可用,不让工具「晚到」。
// 取件结果是 data: 等不可分享地址时才收起分享。
const shareVisible = !!onShareImage && !!activeImage && !activeIsVideo
&& (!activeUri || canShareLightboxImage(activeUri));
const shareEnabled = shareVisible && activeActionsReady;
const handleShare = useCallback(() => {
if (!activeImage || !activeUri || !activeActionsReady || !onShareImage || sharingRef.current || submittingRef.current) return;
const state = resolveMap[activeImage.url];
const mimeType = (state?.status === 'ready' ? state.media.mimeType : undefined)
?? activeImage.payload.media.mimeType;
const sizeBytes = state?.status === 'ready' ? state.media.size : undefined;
sharingRef.current = true;
setSharing(true);
void Promise.resolve()
.then(() =>
onShareImage(activeImage.payload.media, activeUri, mimeType, sizeBytes),
)
.catch(() => {
// 与标注提交一致,宿主负责显示具体分享错误。
})
.finally(() => {
sharingRef.current = false;
setSharing(false);
});
}, [activeImage, activeUri, activeActionsReady, onShareImage, resolveMap]);
// 活跃页 MIME:取件结果优先,保留附件已知类型,最后兜底 URI 后缀。
const activeMimeType = ((activeResolveState?.status === 'ready'
? activeResolveState.media.mimeType
: undefined) ?? activeImage?.payload.media.mimeType)?.split(';', 1)[0].trim().toLowerCase();
// 取件未完成时按原始地址判断格式,让画笔从打开起就在(置灰到可画)。
const activeFormatUri = activeUri ?? activeImage?.payload.media.url ?? '';
const activeLooksGif = /\.gif(?:[?#]|$)/i.test(activeFormatUri.split('?')[0] ?? activeFormatUri);
const activeLooksSvg = /\.svg(?:[?#]|$)/i.test(activeFormatUri) || /^data:image\/svg\+xml[;,]/i.test(activeFormatUri);
const annotateVisible = !!annotation
&& !!activeImage
&& !activeIsVideo
&& canAnnotateImageMime(activeMimeType)
&& !activeLooksGif
&& !activeLooksSvg;
// 画笔要等图片自然尺寸就位(坐标换算基准),否则进入标注后作画静默无效:
// 此前按钮置灰禁用,与撤销的禁用态同观感。宿主给出暂不可标注的原因时,按钮
// 同样置灰但可点,点按说明原因(否则用户不知道为什么不能画)。
const annotateReady = annotateVisible && activeActionsReady && !!activeNaturalSize;
const annotateBlockedReason = annotateReady && activeImage
? annotation?.annotationBlockedReason?.(activeImage)
: undefined;
const annotateEnabled = annotateReady && !annotateBlockedReason;
const enterAnnotationMode = useCallback(() => {
if (!annotateReady || submittingRef.current || sharingRef.current) return;
// 点按时重新询问宿主:替换上传可能在上次渲染后已落定,避免弹出过期原因。
const blockedReason = activeImage ? annotation?.annotationBlockedReason?.(activeImage) : undefined;
if (blockedReason) {
Alert.alert(t('message.lightbox.annotateUnavailableTitle'), blockedReason);
return;
}
setIsAnnotating(true);
}, [annotateReady, activeImage, annotation, t]);
// 独立直发(发送到对话):不要求可标注——gif 等不可画的图同样能转发。
const directSubmitVisible = !!annotation?.allowDirectSubmit && !!activeImage && !activeIsVideo;
const directSubmitEnabled = directSubmitVisible && activeActionsReady;
const handleSubmitAnnotation = useCallback(() => {
if (!annotation || !activeImage || !activeUri || !activeActionsReady || submittingRef.current || sharingRef.current) return;
submittingRef.current = true;
setAnnotationSubmitting(true);
// 点击提交时另一根手指可能还在画,把屏幕上最后一笔也纳入同一快照。
const visibleStrokes = draftStrokeRef.current ? [...strokes, draftStrokeRef.current] : strokes;
// 提交期间会忽略抬手回调,先收存草稿,失败后继续画也不会覆盖这一笔。
setStrokes(visibleStrokes);
draftStrokeRef.current = null;
setDraftStroke(null);
const submittedStrokes = visibleStrokes.map((s) => ({ points: [...s.points] }));
void Promise.resolve()
.then(() => annotation.onSubmit(activeImage, activeUri, submittedStrokes, {
mimeType: activeMimeType,
...(activeNaturalSize
? { naturalWidth: activeNaturalSize.width, naturalHeight: activeNaturalSize.height }
: {}),
}))
.then(() => onCloseRef.current())
.catch(() => {
// 宿主已提示错误;停留在标注模式让用户重试或放弃。
})
.finally(() => {
submittingRef.current = false;
setAnnotationSubmitting(false);
});
}, [annotation, activeImage, activeUri, activeActionsReady, activeMimeType, activeNaturalSize, strokes]);
// Android 物理返回键触发 Modal.onRequestClose,不受手势层/按钮层的
// isAnnotating 禁用覆盖(review 发现:会绕开"标注模式中关闭均禁用"保护
// 直接整体关闭 lightbox,未保存笔迹丢失)。标注中改为退出标注模式(有改动
// 先确认;autoAnnotate 放弃即关闭),提交中忽略返回键,非标注态才走原始关闭。
const handleRequestClose = useCallback(() => {
if (submittingRef.current) return;
if (isAnnotating) {
exitAnnotationMode();
return;
}
onCloseRef.current();
}, [isAnnotating, exitAnnotationMode]);
// iOS 沉浸式隐藏状态栏:经宿主屏的 screen option 走 VC-based 通道(iOS 27 起
// RN StatusBar 全局 API 失效;transparent Modal 不接管状态栏,穿透到宿主屏)。
// Android 继续用 Modal 内组件式 <StatusBar hidden>,不走 RNS 双轨。
// 只触碰 statusBarHidden 一个键,泛型收窄到最小面。
const navigation = useNavigation<{
setOptions: (options: { statusBarHidden: boolean }) => void;
}>();
useEffect(() => {
if (Platform.OS !== 'ios') return;
navigation.setOptions({ statusBarHidden: true });
return () => navigation.setOptions({ statusBarHidden: false });
}, [navigation]);
return (
<Modal
animationType="fade"
onRequestClose={handleRequestClose}
statusBarTranslucent
supportedOrientations={['portrait', 'landscape']}
transparent
visible
>
{Platform.OS === 'android' ? <StatusBar hidden /> : null}
<GestureHandlerRootView
onAccessibilityEscape={handleRequestClose}
style={styles.root}
testID="message.imageLightbox"
>
<Animated.View pointerEvents="none" style={[styles.backdrop, backdropStyle]} />
<FlatList
data={images}
decelerationRate="fast"
getItemLayout={(_, index) => ({ length: width, offset: width * index, index })}
horizontal
initialScrollIndex={initialIndex}
keyExtractor={(image) => image.key}
onMomentumScrollEnd={(event) => {
const index = lightboxPageIndex(event.nativeEvent.contentOffset.x, width, images.length);
const image = images[index];
setActivePage({ key: image?.key, url: image?.url, galleryImageKey: image?.payload.galleryImageKey,
galleryImageSlot: image?.payload.galleryImageSlot, index });
}}
pagingEnabled
ref={listRef}
renderItem={({ item, index }) => (item.payload.media.kind === 'video' ? (
<LightboxVideoPage
active={index === activeIndex}
height={height}
image={item}
insetBottom={insets.bottom}
// 让出顶部关闭 / 页码一行,系统播放控件不被压住。
insetTop={insets.top + 64}
onRetry={handleRetryPage}
onToggleChrome={toggleChrome}
previewUri={previewUriFor(item)}
resolveState={item.payload.media.previewable ? null : resolveMap[item.url] ?? null}
uri={displayUriFor(item)}
width={width}
/>
) : (
<LightboxPage
active={index === activeIndex}
annotating={index === activeIndex && isAnnotating}
// 活跃页显示编辑中的笔迹;预取的相邻页显示各自的既有笔迹(托盘
// 多图再编辑时翻页不闪空)。
annotationDraftStroke={index === activeIndex ? draftStroke : null}
annotationStrokes={index === activeIndex
? strokes
: annotation?.initialStrokesFor?.(item) ?? EMPTY_STROKES}
chromeHidden={chromeHidden}
chromeVisible={chromeShown && chromeInteractive}
dismissY={dismissY}
height={height}
image={item}
interactionDisabled={annotationSubmitting || index !== activeIndex}
naturalSize={naturalSizes[item.key] ?? null}
onChromeBusy={handleChromeBusy}
onDrawPoint={handleDrawPoint}
onImageError={handleImageLoadError}
onImageLoaded={handleImageLoaded}
onNaturalSize={handleNaturalSize}
onRequestClose={handleRequestClose}
onRetry={handleRetryPage}
onToggleChrome={toggleChrome}
onZoomChange={setZoomed}
previewUri={previewUriFor(item)}
resolveState={item.payload.media.previewable ? null : resolveMap[item.url] ?? null}
uri={displayUriFor(item)}
width={width}
/>
))}
// 单图同样开启:iOS 横向拖到边缘有系统回弹,与多图首尾页手感一致。
scrollEnabled={!zoomed && !isAnnotating && !annotationSubmitting}
showsHorizontalScrollIndicator={false}
windowSize={3}
/>
<Animated.View
pointerEvents={chromeInteractive && chromeShown ? 'box-none' : 'none'}
// 整个操作层避开横屏两侧切口,让关闭、文件标题和所有底栏共用安全边界。
style={[styles.chrome, chromeStyle, {
left: insets.left,
right: insets.right,
paddingBottom: insets.bottom + 16,
paddingTop: insets.top + 8,
}]}
testID="message.imageLightboxChrome"
>
{!isAnnotating && !showFileHeader ? (
<Pressable
accessibilityLabel={t('message.lightbox.closeImage')}
accessibilityRole="button"
disabled={annotationSubmitting}
onPress={handleRequestClose}
style={[styles.closeButton, { top: insets.top + 8 }]}
testID="message.imageLightboxCloseButton"
>
<X color="#ffffff" size={iconSize.action} strokeWidth={iconStroke.regular} />
</Pressable>
) : null}
{isAnnotating ? (
// 标注模式 chrome(对齐桌面):底部工具栏切换为 取消 / 撤销 / 提交
// 三项;翻页/下滑/单击关闭均已在手势层禁用,页码与分享隐藏。
<View pointerEvents="box-none" style={[styles.actionBar, { bottom: insets.bottom + 12 }]}>
<View style={styles.actionBarPill}>
<Pressable
accessibilityLabel={t('message.lightbox.cancelAnnotation')}
disabled={annotationSubmitting}
hitSlop={8}
onPress={exitAnnotationMode}
style={styles.actionItem}
testID="message.imageLightboxAnnotationCancel"
>
<X color="#ffffff" size={iconSize.action} strokeWidth={iconStroke.regular} />
<Text style={styles.actionLabel}>{t('message.lightbox.cancel')}</Text>
</Pressable>
<Pressable
accessibilityLabel={t('message.lightbox.undoLastStroke')}
disabled={strokes.length === 0 || annotationSubmitting}
hitSlop={8}
onPress={undoLastStroke}
style={styles.actionItem}
testID="message.imageLightboxAnnotationUndo"
>
<Undo2
color={strokes.length > 0 ? '#ffffff' : DISABLED_ICON_COLOR}
size={iconSize.action}
strokeWidth={iconStroke.regular}
/>
<Text style={[styles.actionLabel, strokes.length === 0 && styles.actionLabelDisabled]}>{t('message.lightbox.undo')}</Text>
</Pressable>
<Pressable
accessibilityLabel={annotation?.submitLabel ?? t('message.lightbox.done')}
disabled={annotationSubmitting}
hitSlop={8}
onPress={handleSubmitAnnotation}
style={styles.actionItem}
testID="message.imageLightboxAnnotationSubmit"
>
{annotationSubmitting ? (
<ActivityIndicator color="#ffffff" size="small" />
) : (
<MessageSquarePlus color="#ffffff" size={iconSize.action} strokeWidth={iconStroke.regular} />
)}
<Text style={styles.actionLabel}>{annotation?.submitLabel ?? t('message.lightbox.done')}</Text>
</Pressable>
</View>
</View>
) : showFileHeader ? (
<View pointerEvents="box-none" style={styles.fileHeader}>
<Pressable accessibilityLabel={t('message.lightbox.done')}
accessibilityRole="button"
disabled={annotationSubmitting}
hitSlop={10} onPress={handleRequestClose} testID="message.imageLightboxDone">
<Text style={styles.fileHeaderDone}>{t('message.lightbox.done')}</Text>
</Pressable>
<View pointerEvents="none" style={styles.fileHeaderTitleCol}>
<Text numberOfLines={1} style={styles.fileHeaderTitle} testID="message.imageLightboxTitle">
{activeImage?.title ?? ''}
</Text>
<Text numberOfLines={1} style={styles.fileHeaderMeta}>
{[pageLabel, activeImage?.subtitle].filter(Boolean).join(' · ')}
</Text>
</View>
{shareVisible ? (
<Pressable
accessibilityLabel={t('message.lightbox.shareImage')}
accessibilityRole="button"
accessibilityState={{ busy: sharing }}
disabled={!shareEnabled || sharing || annotationSubmitting}
hitSlop={10}
onPress={handleShare}
testID="message.imageLightboxShareButton"
>
{sharing ? (
<ActivityIndicator color="#ffffff" size="small" />
) : <ShareIcon color={shareEnabled ? '#ffffff' : DISABLED_ICON_COLOR} size={iconSize.action} strokeWidth={iconStroke.regular} />}
</Pressable>
) : (
<View style={styles.fileHeaderShareSpacer} />
)}
</View>
) : pageLabel ? (
<Text style={styles.pageLabel} testID="message.imageLightboxPageLabel">{pageLabel}</Text>
) : null}
{isAnnotating ? null : extraActions && extraActions.length > 0 ? (
<View pointerEvents="box-none" style={[styles.actionBar, { bottom: insets.bottom + 12 }]}>
<View style={styles.actionBarPill}>
{annotateVisible ? (
<Pressable
accessibilityHint={annotateBlockedReason}
accessibilityLabel={annotateBlockedReason
? t('message.lightbox.annotateImageUnavailable')
: t('message.lightbox.annotateImage')}
accessibilityState={{ disabled: !annotateReady }}
disabled={annotationSubmitting || sharing || !annotateReady}
hitSlop={8}
onPress={enterAnnotationMode}
style={styles.actionItem}
testID="message.imageLightboxAnnotateButton"
>
<Pen
color={annotateEnabled ? '#ffffff' : DISABLED_ICON_COLOR}
size={iconSize.action}
strokeWidth={iconStroke.regular}
/>
<Text style={[styles.actionLabel, !annotateEnabled && styles.actionLabelDisabled]}>{t('message.lightbox.annotate')}</Text>
</Pressable>
) : null}
{extraActions.map((action) => (
<Pressable
accessibilityLabel={action.label}
disabled={annotationSubmitting || sharing}
hitSlop={8}
key={action.key}
onPress={() => activeImage && action.onPress(activeImage)}
style={styles.actionItem}
testID={`message.imageLightboxAction.${action.key}`}
>
<action.icon color="#ffffff" size={iconSize.action} strokeWidth={iconStroke.regular} />
<Text style={styles.actionLabel}>{action.label}</Text>
</Pressable>
))}
{shareVisible && !showFileHeader ? (
<Pressable
accessibilityLabel={t('message.lightbox.shareImage')}
accessibilityRole="button"
accessibilityState={{ busy: sharing }}
disabled={!shareEnabled || sharing || annotationSubmitting}
hitSlop={8}
onPress={handleShare}
style={styles.actionItem}
testID="message.imageLightboxShareButton"
>
{sharing ? (
<ActivityIndicator color="#ffffff" size="small" />
) : (
<ShareIcon
color={shareEnabled ? '#ffffff' : DISABLED_ICON_COLOR}
size={iconSize.action}
strokeWidth={iconStroke.regular}
/>
)}
<Text style={[styles.actionLabel, !shareEnabled && styles.actionLabelDisabled]}>
{t('message.lightbox.exportShare')}
</Text>
</Pressable>
) : null}
</View>
</View>
) : shareVisible || annotateVisible || directSubmitVisible ? (
// 聊天 chrome(对齐桌面):底部工具栏 [标注][发送到对话] | [导出/分享]。
// 分享覆盖桌面「复制/另存为/打开」的能力面(系统分享单),分隔线左侧
// 是「进对话」组、右侧是「出 app」组。
<View pointerEvents="box-none" style={[styles.actionBar, { bottom: insets.bottom + 12 }]}>
<View style={styles.actionBarPill}>
{annotateVisible ? (
<Pressable
accessibilityHint={annotateBlockedReason}
accessibilityLabel={annotateBlockedReason
? t('message.lightbox.annotateImageUnavailable')
: t('message.lightbox.annotateImage')}
accessibilityState={{ disabled: !annotateReady }}
disabled={annotationSubmitting || sharing || !annotateReady}
hitSlop={8}
onPress={enterAnnotationMode}
style={styles.actionItem}
testID="message.imageLightboxAnnotateButton"
>
<Pen
color={annotateEnabled ? '#ffffff' : DISABLED_ICON_COLOR}
size={iconSize.action}
strokeWidth={iconStroke.regular}
/>
<Text style={[styles.actionLabel, !annotateEnabled && styles.actionLabelDisabled]}>
{t('message.lightbox.annotate')}
</Text>
</Pressable>
) : null}
{directSubmitVisible ? (
<Pressable
accessibilityLabel={annotation?.submitLabel ?? t('message.lightbox.sendToChat')}
accessibilityState={{ disabled: !directSubmitEnabled }}
disabled={!directSubmitEnabled || annotationSubmitting || sharing}
hitSlop={8}
onPress={handleSubmitAnnotation}
style={styles.actionItem}
testID="message.imageLightboxSendToChatButton"
>
{annotationSubmitting ? (
<ActivityIndicator color="#ffffff" size="small" />
) : (
<MessageSquarePlus
color={directSubmitEnabled ? '#ffffff' : DISABLED_ICON_COLOR}
size={iconSize.action}
strokeWidth={iconStroke.regular}
/>
)}
<Text style={[styles.actionLabel, !directSubmitEnabled && styles.actionLabelDisabled]}>
{annotation?.submitLabel ?? t('message.lightbox.sendToChat')}
</Text>
</Pressable>
) : null}
{shareVisible && (annotateVisible || directSubmitVisible) ? (
<View style={styles.actionDivider} />
) : null}
{shareVisible ? (
<Pressable
accessibilityLabel={t('message.lightbox.shareImage')}
accessibilityRole="button"
accessibilityState={{ busy: sharing }}
disabled={!shareEnabled || sharing || annotationSubmitting}
hitSlop={8}
onPress={handleShare}
style={styles.actionItem}
testID="message.imageLightboxShareButton"
>
{sharing ? (
<ActivityIndicator color="#ffffff" size="small" />
) : (
<ShareIcon
color={shareEnabled ? '#ffffff' : DISABLED_ICON_COLOR}
size={iconSize.action}
strokeWidth={iconStroke.regular}
/>
)}
<Text style={[styles.actionLabel, !shareEnabled && styles.actionLabelDisabled]}>
{t('message.lightbox.exportShare')}
</Text>
</Pressable>
) : null}
</View>
</View>
) : null}
</Animated.View>
</GestureHandlerRootView>
</Modal>
);
});
/** 置灰操作的图标色(与 actionLabelDisabled 同值)。 */
const DISABLED_ICON_COLOR = 'rgba(255,255,255,0.35)';
/** 空笔迹常量:非活跃页无既有笔迹时复用同一引用,保住 LightboxPage 的 memo。 */
const EMPTY_STROKES: readonly AnnotationStroke[] = [];
/** 单页:图片手势(捏合/平移/双击/单击/下滑)+ 取件中/失败态 + 标注 overlay。 */
const LightboxPage = memo(function LightboxPage({
active,
annotating,
annotationDraftStroke,
annotationStrokes,
chromeHidden,
chromeVisible,
dismissY,
height,
image,
interactionDisabled,
naturalSize,
onChromeBusy,
onDrawPoint,
onImageError,
onImageLoaded,
onNaturalSize,
onRequestClose,
onRetry,
onToggleChrome,
onZoomChange,
previewUri,
resolveState,
uri,
width,
}: {
active: boolean;
interactionDisabled: boolean;
/** 标注模式(仅活跃页):单指作画、禁单击/下滑关闭与双击缩放,双指仍可缩放平移。 */
annotating: boolean;
/** 进行中的一笔(仅活跃页非空)。 */
annotationDraftStroke: AnnotationStroke | null;
/** 已落笔迹(活跃页=编辑态;其它页=各自的既有笔迹,只读叠加显示)。 */
annotationStrokes: readonly AnnotationStroke[];
chromeHidden: SharedValue<number>;
chromeVisible: boolean;
dismissY: SharedValue<number>;
height: number;
image: MobileMessageGalleryImage;
/** 图片自然尺寸(overlay 坐标基准;未知时 overlay 不渲染、画笔不采点)。 */
naturalSize: { width: number; height: number } | null;
/** 捏合/平移开始与结束时通知父层开关 chrome 触摸。 */
onChromeBusy(busy: boolean): void;
/** 画笔事件(容器坐标 + 当页 transform 快照),UI 线程经 runOnJS 上抛;
* end 附带手势是否正常结束(第二根手指落下会让画笔手势被取消)。 */
onDrawPoint: (
phase: 'start' | 'move' | 'end',
pointX: number,
pointY: number,
translateX: number,
translateY: number,
scale: number,
gestureSucceeded?: boolean,
) => void;
/** 原生 Image 加载失败(悬空 key 404 等)→ 上抛做一次性 forceRefresh 自愈。
* 带 image 参数的稳定引用;是否接线由本页按 retryable 判定。 */
onImageError?: (image: MobileMessageGalleryImage) => void;
onImageLoaded(image: MobileMessageGalleryImage, media?: MobileResolvedRemoteMedia): void;
onNaturalSize(imageKey: string, size: { width: number; height: number }): void;
onRequestClose(): void;
onRetry(image: MobileMessageGalleryImage): void;
/** 单击:隐藏 / 显示 chrome。 */
onToggleChrome(): void;
onZoomChange(zoomed: boolean): void;
/** 列表缩略图(渐进出图的垫底层);无则退 spinner。见 lightboxImageLayers。 */
previewUri: string | null;
resolveState: PageResolveState | null;
uri: string | null;
width: number;
}) {
const { t } = useTranslation();
const scale = useSharedValue(1);
const savedScale = useSharedValue(1);
const translateX = useSharedValue(0);
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 pinchStartScale = useSharedValue(1);
/** 捏合当前的手指数:变化时重新锚定,先后抬指不让焦点跳变推着图走。 */
const pinchPointers = useSharedValue(2);
const displayedW = useSharedValue(width);
const displayedH = useSharedValue(height);
/** 捏合最后的焦点(容器坐标):捏过最大倍率松手时绕它缩回。 */
const lastFocalX = useSharedValue(0);
const lastFocalY = useSharedValue(0);
const pinchBusy = useSharedValue(0);
const panBusy = useSharedValue(0);
const doubleTapBusy = useSharedValue(0);
/** 平移松手后的惯性滑行 / 越界回弹进行中:手指按下即可接住。 */
const panSettling = useSharedValue(0);
/** 本次按下接住了滑行;若没形成拖动就抬手,要补一次回弹,不能停在越界处。 */
const panCaught = useSharedValue(0);
/** 松手回弹(springToTransform)进行中:位移已有一致的目标,平移松手不另起回弹;落定前锁住翻页。 */
const zoomSettling = useSharedValue(0);
const dragY = useSharedValue(0);
/**
* 已 onLoad 成功的原图地址。存地址而不是 boolean:换图 / 强制重取换 url 后
* 天然失效,不需要额外 effect 复位(漏复位就会让新图那段又回到纯黑)。
*/
const [loadedUri, setLoadedUri] = useState<string | null>(null);
/**
* 已确认加载失败的垫底图地址(同样存地址,换图天然失效)。
* 缩略图的磁盘文件可能被 150MB LRU 或系统清理掉,而取件队列的内存缓存仍持有那个
* 永不过期的 file:// —— 光看 URI 存在会把"没有像素"当成"已经出图",于是 spinner
* 被藏掉、垫底层又画不出东西,整段退回纯黑(PR #1125 review)。
*/
const [failedPreviewUri, setFailedPreviewUri] = useState<string | null>(null);
/**
* 已确证 onError 的原图地址(同样存地址,换图 / 重取换 url 天然失效)。
* 桌面取件图有 forceRefresh 自愈 + 重试按钮兜底,失败终态由父层的 resolveMap 接管;
* 直连 http 图在本页落失败态,用户重试时清除此标记并重新挂载 Image。
*/
const [failedFullUri, setFailedFullUri] = useState<string | null>(null);
// 同一个本地路径重取后可能已有新字节:失败只属于当次取件结果,不能永久封锁 URI。
const [failedFullMedia, setFailedFullMedia] = useState<MobileResolvedRemoteMedia | undefined>();
const [retryRequested, setRetryRequested] = useState(false);
const insets = useSafeAreaInsets();
/**
* 垫底缩略图的像素尺寸:原图未到时用它的宽高比算 contain 显示尺寸,
* 让缩放 / 平移的边界从打开起就对(缩略图与原图同比例)。
*/
const [previewSize, setPreviewSize] = useState<{ uri: string; width: number; height: number } | null>(null);
const layoutSize = naturalSize ?? (previewSize && previewSize.uri === previewUri ? previewSize : null);
const media = image.payload.media;
// 桌面取件图可 forceRefresh;直连图重试只重新挂载原 URI,不走桌面取件。
const retryable = !media.previewable && isDesktopLocalMediaUrl(media.url);
const fullFailed = !!uri && failedFullUri === uri
&& (!retryable || failedFullMedia === resolveState?.media);
const resolvedUnsupported = resolveState?.status === 'ready' && !resolveState.media.previewable;
const originalFailed = resolveState?.status === 'error' || resolvedUnsupported
|| (!retryable && fullFailed) || (!uri && !retryable && !media.previewable);
const layers = lightboxImageLayers({
fullUri: uri,
previewUri,
fullLoaded: !!uri && loadedUri === uri && !fullFailed,
previewFailed: !!previewUri && failedPreviewUri === previewUri,
fullFailedTerminally: originalFailed,
});
// 所有失败统一经图层模型裁决:可用预览优先,没有任何可显示内容才整页报错。
const pageFailed = layers.showFailure;
const showOriginalNotice = active && chromeVisible && layers.showPreview && (originalFailed || retryRequested);
const retryOriginal = () => {
if (retryRequested && !originalFailed) return;
setRetryRequested(true);
if (retryable) onRetry(image);
else {
setFailedFullUri(null);
setLoadedUri(null);
}
};
const reportZoomed = useCallback((value: boolean) => {
onZoomChange(value);
}, [onZoomChange]);
/**
* 倍率与位移一起弹到合法落点。三者同一弹簧、零初速:归一化进度逐帧相同,
* 画面上 p·s + T 线性插值,焦点下那一点全程不漂。调用前 origin 必须已归零。
* 手势松手与尺寸变化(回弹途中原图尺寸到达)共用,翻页锁与落定上报只在这一处。
*/
const springToTransform = useCallback((target: { scale: number; x: number; y: number }) => {
'worklet';
savedScale.value = target.scale;
savedTranslateX.value = target.x;
savedTranslateY.value = target.y;
const scaleMoves = scale.value !== target.scale;
const xMoves = translateX.value !== target.x;
const yMoves = translateY.value !== target.y;
if (!scaleMoves && !xMoves && !yMoves) {
zoomSettling.value = 0;
runOnJS(reportZoomed)(isLightboxZoomed(target.scale));
return;
}
// 先置标记、先锁翻页,再启动动画:减少动态效果下回调会在赋值时同步执行,
// 落定上报必须是最后一次(与双击路径一致)。回到 1x 的回弹期间锁住翻页,
// 否则缩小松手后立刻横划会被翻页抢走、在回弹中途切走当前图。
zoomSettling.value = 1;
runOnJS(reportZoomed)(true);
// 落定回调只挂在一条动画上;被新手势打断(finished=false)时由接管方负责翻页锁。
const onSettled = (finished?: boolean) => {
'worklet';
if (!finished) return;
zoomSettling.value = 0;
runOnJS(reportZoomed)(isLightboxZoomed(savedScale.value));
};
if (scaleMoves) scale.value = withSpring(target.scale, LIGHTBOX_SETTLE_SPRING, onSettled);
if (xMoves) {
translateX.value = withSpring(target.x, LIGHTBOX_SETTLE_SPRING, scaleMoves ? undefined : onSettled);
}
if (yMoves) {
translateY.value = withSpring(
target.y,
LIGHTBOX_SETTLE_SPRING,
scaleMoves || xMoves ? undefined : onSettled,
);
}
// 共享值引用恒定,只随 reportZoomed 重建
// eslint-disable-next-line react-hooks/exhaustive-deps
}, [reportZoomed]);
useEffect(() => {
const size = lightboxContainedSize(
width,
height,
layoutSize?.width ?? 0,
layoutSize?.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;
}
// 松手回弹途中:直接改 live 会打断回弹,落定回调不触发,翻页一直锁着、倍率
// 也可能停在范围外。把目标收进新边界,从当前帧重新发起同一次回弹。
if (zoomSettling.value) {
const next = reclampLightboxPan(
savedTranslateX.value,
savedTranslateY.value,
width,
height,
savedScale.value,
size.width,
size.height,
);
springToTransform({ scale: savedScale.value, x: next.x, y: 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
}, [layoutSize?.width, layoutSize?.height, width, height]);
// 翻走 / 换图时复位缩放与位移,避免回到本页时残留上次的缩放态。失败态同样
// 复位:加载中放大了垫底图、随后取件失败时手势层被卸掉,不复位就停在「已放大」,
// 父层锁着翻页、失败页又没有双击可缩回,只能关掉重开。
const transformReset = !active || pageFailed;
useEffect(() => {
if (!transformReset) return;
scale.value = 1;
savedScale.value = 1;
translateX.value = 0;
translateY.value = 0;
savedTranslateX.value = 0;
savedTranslateY.value = 0;
originX.value = 0;
originY.value = 0;
pinchBusy.value = 0;
panBusy.value = 0;
doubleTapBusy.value = 0;
panSettling.value = 0;
panCaught.value = 0;
zoomSettling.value = 0;
dragY.value = 0;
chromeHidden.value = 0;
onChromeBusy(false);
// 只有活跃页拥有父层的翻页锁;非活跃页复位不能改写当前页的放大状态。
if (active) onZoomChange(false);
// 共享值的写入不需要依赖追踪,这里只关心复位条件的翻转时机
// eslint-disable-next-line react-hooks/exhaustive-deps
}, [transformReset]);
const gesture = useMemo(() => {
// 新手势接管当前帧,必须同时停掉缩放与两轴位移,避免旧动画继续推着图片走。
const stopTransformAnimation = () => {
'worklet';
doubleTapBusy.value = 0;
panSettling.value = 0;
panCaught.value = 0;
zoomSettling.value = 0;
cancelAnimation(scale);
cancelAnimation(translateX);
cancelAnimation(translateY);
};
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 settlePinch = () => {
'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;
translateX.value = bakedX;
translateY.value = bakedY;
springToTransform(lightboxPinchSettle({
scale: scale.value,
translateX: bakedX,
translateY: bakedY,
focalX: lightboxPinchOrigin(lastFocalX.value, width),
focalY: lightboxPinchOrigin(lastFocalY.value, height),
containerWidth: width,
containerHeight: height,
displayedWidth: displayedW.value,
displayedHeight: displayedH.value,
}));
};
/** 单轴松手:越界弹簧回边界;边界内有速度则惯性滑行,滑到边界由橡皮筋衰减冲过再回。 */
const releasePanAxis = (
value: SharedValue<number>,
velocity: number,
containerSize: number,
displayedSize: number,
) => {
'worklet';
const release = lightboxPanRelease(value.value, velocity, containerSize, scale.value, displayedSize);
if (release.kind === 'settle') {
value.value = withSpring(release.to, { ...LIGHTBOX_SETTLE_SPRING, velocity });
} else if (release.kind === 'fling') {
value.value = withDecay({ velocity, clamp: [release.min, release.max], rubberBandEffect: true });
}
};
const settlePan = (velocityX: number, velocityY: number) => {
'worklet';
// 倍率回弹被拖动打断时可能停在两端之外:连同位移按画面中心收回合法落点。
if (scale.value > LIGHTBOX_MAX_SCALE || scale.value < LIGHTBOX_MIN_SCALE) {
springToTransform(lightboxPinchSettle({
scale: scale.value,
translateX: translateX.value,
translateY: translateY.value,
focalX: 0,
focalY: 0,
containerWidth: width,
containerHeight: height,
displayedWidth: displayedW.value,
displayedHeight: displayedH.value,
}));
return;
}
releasePanAxis(translateX, velocityX, width, displayedW.value);
releasePanAxis(translateY, velocityY, height, displayedH.value);
panSettling.value = 1;
};
/**
* 以当前画面为起点锚定捏合:捏合开始与手指数变化时共用。eventScale 是此刻
* 手势自身的累计倍率,倍率基准除掉它,下一帧 savedScale·eventScale 与画面一致。
*/
const anchorPinch = (focalX: number, focalY: number, eventScale: number) => {
'worklet';
// 倍率起点存「手指量」而非画面量:回弹途中再捏时画面可能处在橡皮筋区,
// 直接当起点会让第一帧按阻尼重新映射而跳一下。
savedScale.value = unrubberLightboxScale(scale.value) / (eventScale > 0 ? eventScale : 1);
// 锚点取手指下那一点的图片坐标,已放大 / 平移后二次捏合才绕手指缩放。
const bakedX = bakeLightboxOrigin(translateX.value, originX.value, scale.value);
const bakedY = bakeLightboxOrigin(translateY.value, originY.value, scale.value);
originX.value = lightboxPinchAnchor(focalX, width, bakedX, scale.value);
originY.value = lightboxPinchAnchor(focalY, height, bakedY, scale.value);
// 已放大时 origin 会立刻贡献 origin*(1-scale);扣掉等量位移,二次捏合不跳。
translateX.value = compensateLightboxOrigin(bakedX, originX.value, scale.value);
translateY.value = compensateLightboxOrigin(bakedY, originY.value, scale.value);
// 起点存 bake 后的画面位移(几何量);每帧按当前倍率的边界换算手指量,
// 不跨倍率复用起始倍率下的换算结果(见 lightboxPinchTranslation)。
savedTranslateX.value = bakedX;
savedTranslateY.value = bakedY;
pinchStartScale.value = scale.value;
startFocalX.value = focalX;
startFocalY.value = focalY;
};
// 焦点捏合:起点锁定 origin,缩放绕焦点;浏览态跟手质心,标注态只改 scale
// (平移交给双指 pan,避免 Simultaneous 下位移被加两遍)。
const pinch = Gesture.Pinch()
.enabled(!interactionDisabled)
.onStart((event) => {
pinchBusy.value = 1;
stopTransformAnimation();
hideChrome();
// 捏合一开始就锁死翻页,不等 JS zoomed 提交;否则松手后立刻左右拖
// 会被 pagingEnabled 的 FlatList 抢走,当前页直接滑走。
runOnJS(reportZoomed)(true);
// 下滑半途改捏合:关掉正在进行的 dismiss 位移,不把图和背景留在半透明上。
dragY.value = 0;
dismissY.value = 0;
anchorPinch(event.focalX, event.focalY, 1);
pinchPointers.value = event.numberOfPointers ?? 2;
lastFocalX.value = event.focalX;
lastFocalY.value = event.focalY;
})
.onChange((event) => {
// 两指先后抬起(或中途再加一指)时手势不结束,焦点却从双指中点跳到剩下
// 那根手指上,倍率基准也可能重置:按当前画面重新锚定,不让这一跳推着图走。
const pointers = event.numberOfPointers ?? pinchPointers.value;
if (pointers !== pinchPointers.value) {
pinchPointers.value = pointers;
anchorPinch(event.focalX, event.focalY, event.scale);
}
// 捏过 1x / 最大倍率不再硬卡:阻尼继续缩放,松手再弹回(settlePinch)。
scale.value = rubberBandLightboxScale(savedScale.value * event.scale);
// 松手绕焦点缩回只认双指焦点:单指余下的落点不是用户捏的中心。
if (pointers >= 2) {
lastFocalX.value = event.focalX;
lastFocalY.value = event.focalY;
}
if (annotating) return;
// 锚点跟手;越过图片边界按当前倍率的边界阻尼而不是硬钳,焦点附近捏合时
// 图不再「粘」在边上,回弹途中再捏时锚点也不从手指下滑开。
const next = {
x: lightboxPinchTranslation(
savedTranslateX.value,
originX.value,
pinchStartScale.value,
scale.value,
event.focalX - startFocalX.value,
width,
displayedW.value,
),
y: lightboxPinchTranslation(
savedTranslateY.value,
originY.value,
pinchStartScale.value,
scale.value,
event.focalY - startFocalY.value,
height,
displayedH.value,
),
};
translateX.value = next.x;
translateY.value = next.y;
})
.onFinalize(() => {
if (!pinchBusy.value) return;
settlePinch();
pinchBusy.value = 0;
maybeShowChrome();
});
// 浏览:单指平移,未放大时 fail,避免与 pinch 抢 2 指。
// 标注:恰好双指平移,1x 也可挪视野。
const panZoomed = Gesture.Pan()
.enabled(!interactionDisabled)
.minPointers(annotating ? 2 : 1)
.maxPointers(annotating ? 2 : 1)
.onTouchesDown((_event, state) => {
if (!annotating && !isLightboxZoomed(scale.value)) {
state.fail();
return;
}
// 手指按住正在滑行 / 回弹的图:就地停住,对齐系统相册的「接住」手感。
if (panSettling.value) {
cancelAnimation(translateX);
cancelAnimation(translateY);
panSettling.value = 0;
panCaught.value = 1;
}
})
.onStart(() => {
// 浏览态的位移在捏合期间归捏合:两指先后抬起时余下那根手指可能激活单指
// 平移,它若接手就会改写捏合的起点、叠加位移,松手再甩出一段惯性。
if (!annotating && pinchBusy.value) return;
panBusy.value = 1;
stopTransformAnimation();
hideChrome();
savedTranslateX.value = translateX.value;
savedTranslateY.value = translateY.value;
})
.onChange((event) => {
if (!panBusy.value || (!annotating && pinchBusy.value)) return;
// 标注双指 pan 与 off-center pinch Simultaneous,origin 常非 0;
// 浏览单指 pan 的 origin 已 bake 归零。越界部分走橡皮筋:到了边缘仍可
// 继续拖(越拖越沉),松手再弹回(settlePan)。
const next = dragLightboxVisualPan(
translateX.value,
translateY.value,
event.changeX,
event.changeY,
originX.value,
originY.value,
width,
height,
scale.value,
displayedW.value,
displayedH.value,
);
translateX.value = next.x;
translateY.value = next.y;
})
.onFinalize((event) => {
// Tap 也会让未激活的 Pan 走 FAILED → finalize。它不拥有位移,
// 不能把双击缩回的 saved=0 覆盖成动画中途的旧偏移。
if (!panBusy.value) {
// 接住滑行后没拖就抬手:图可能停在越界处,补一次回弹。双击 / 捏合
// 已接管时由它们负责落点(stopTransformAnimation 会清掉 panCaught)。
if (panCaught.value && !pinchBusy.value && !doubleTapBusy.value) {
panCaught.value = 0;
settlePan(0, 0);
}
return;
}
if (!annotating && pinchBusy.value) {
// 平移先起、捏合随后接管:起点与落点都归捏合,不能覆盖它的 saved 位移。
panBusy.value = 0;
maybeShowChrome();
return;
}
savedTranslateX.value = translateX.value;
savedTranslateY.value = translateY.value;
panBusy.value = 0;
if (!pinchBusy.value) {
// 回弹进行中时位移已随之弹向一致落点,这里不另起动画抢它。
if (!zoomSettling.value) settlePan(event.velocityX ?? 0, event.velocityY ?? 0);
// 回弹(含刚由 settlePan 发起的)由 springToTransform 管翻页锁,落定时再上报。
if (!zoomSettling.value) runOnJS(reportZoomed)(isLightboxZoomed(scale.value));
}
maybeShowChrome();
});
const panDismiss = Gesture.Pan()
.enabled(!annotating && !interactionDisabled)
.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, 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 && !interactionDisabled)
.numberOfTaps(2)
.maxDistance(LIGHTBOX_TAP_MAX_DISTANCE)
.onEnd((event, success) => {
if (!success || pinchBusy.value || panBusy.value) return;
const next = nextDoubleTapScale(
doubleTapBusy.value ? savedScale.value : scale.value,
);
stopTransformAnimation();
originX.value = 0;
originY.value = 0;
dragY.value = 0;
dismissY.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;
runOnJS(reportZoomed)(isLightboxZoomed(savedScale.value));
};
if (!isLightboxZoomed(next)) {
savedScale.value = 1;
savedTranslateX.value = 0;
savedTranslateY.value = 0;
// 动画完成前继续锁住翻页;减少动态效果下回调可同步执行,先写目标。
scale.value = withTiming(1);
translateX.value = withTiming(0);
translateY.value = withTiming(0, undefined, clearDoubleTapBusy);
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,
);
savedScale.value = next;
savedTranslateX.value = tx;
savedTranslateY.value = ty;
runOnJS(reportZoomed)(true);
scale.value = withTiming(next);
translateX.value = withTiming(tx);
translateY.value = withTiming(ty, undefined, clearDoubleTapBusy);
});
const singleTap = Gesture.Tap()
.enabled(!annotating && !interactionDisabled)
.numberOfTaps(1)
.maxDistance(LIGHTBOX_TAP_MAX_DISTANCE)
.onEnd((_event, success) => {
// 单击只切换 chrome 显隐,不关闭(关闭走按钮 / 下滑 / 系统返回)。
if (success) runOnJS(onToggleChrome)();
});
// 画笔:单指跟手采点(worklet 只搬运坐标 + transform 快照,归一化在 JS 侧
// 纯函数完成);第二根手指落下时本手势被取消(success=false):已画出一段的
// 半笔照常落笔,屏幕路径极短的(捏合起手误触的点 / 小短线)由 JS 侧丢弃。
const panDraw = Gesture.Pan()
.enabled(annotating && !interactionDisabled)
.maxPointers(1)
.minDistance(0)
.onStart((event) => {
runOnJS(onDrawPoint)('start', event.x, event.y, translateX.value, translateY.value, scale.value);
})
.onUpdate((event) => {
runOnJS(onDrawPoint)('move', event.x, event.y, translateX.value, translateY.value, scale.value);
})
.onFinalize((_event, success) => {
runOnJS(onDrawPoint)('end', 0, 0, 0, 0, 1, success);
});
return Gesture.Simultaneous(
Gesture.Exclusive(doubleTap, singleTap),
pinch,
panZoomed,
panDismiss,
panDraw,
);
// 共享值引用恒定,只有布尔开关与尺寸变化需要重建手势。不再把 zoomed
// 放进 deps:捏合结束改 React 状态会整图重建手势图,正是卡顿来源。
// eslint-disable-next-line react-hooks/exhaustive-deps
}, [
annotating,
interactionDisabled,
width,
height,
onRequestClose,
reportZoomed,
onDrawPoint,
onChromeBusy,
onToggleChrome,
springToTransform,
]);
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 },
],
}));
// 标注 overlay 的锚定矩形(contain 1x):其中心恒等于容器中心,与图片层共用
// 同一 translate/scale transform 时缩放中心一致,视觉完全跟随(纯函数,可单测)。
const annotationBase = useMemo(
() => (naturalSize ? annotationBaseRect(width, height, naturalSize.width, naturalSize.height) : null),
[naturalSize, width, height],
);
const overlayVisible = !!uri && !!annotationBase && !!naturalSize
&& (annotationStrokes.length > 0 || !!annotationDraftStroke);
const overlayStrokeWidth = naturalSize
? annotationStrokeWidth(naturalSize.width, naturalSize.height)
: 0;
const overlayOutlineWidth = annotationOutlineWidth(overlayStrokeWidth);
// 已落笔迹的两层 path 元素按(笔迹, 尺寸)记忆:作画时每个 move 只重算进行中
// 那一笔,已有笔迹的 path 字符串与元素引用不变,React 直接跳过它们。
const committedOutlinePaths = useMemo(() => (naturalSize
? annotationStrokes.map((stroke, index) => (
<Path
d={annotationStrokeToSvgPath(stroke, naturalSize.width, naturalSize.height)}
fill="none"
key={`outline-${index}`}
stroke={ANNOTATION_OUTLINE_COLOR}
strokeLinecap="round"
strokeLinejoin="round"
strokeWidth={overlayOutlineWidth}
/>
))
: null), [annotationStrokes, naturalSize, overlayOutlineWidth]);
const committedStrokePaths = useMemo(() => (naturalSize
? annotationStrokes.map((stroke, index) => (
<Path
d={annotationStrokeToSvgPath(stroke, naturalSize.width, naturalSize.height)}
fill="none"
key={`stroke-${index}`}
stroke={ANNOTATION_STROKE_COLOR}
strokeLinecap="round"
strokeLinejoin="round"
strokeWidth={overlayStrokeWidth}
/>
))
: null), [annotationStrokes, naturalSize, overlayStrokeWidth]);
const draftPathD = naturalSize && annotationDraftStroke
? annotationStrokeToSvgPath(annotationDraftStroke, naturalSize.width, naturalSize.height)
: null;
return (
<View style={{ height, width }}>
{!pageFailed ? (
// 取件中也挂手势层:垫底缩略图从打开起就能捏合 / 双击放大、单击切换 chrome,
// 原图到达后在同一层里替换像素,缩放状态不丢。
<GestureDetector gesture={gesture}>
<Animated.View collapsable={false} style={styles.pageFill}>
{/*
渐进出图的垫底层:原图字节还在下载时,先用列表已解码的缩略图占住
整屏(此前这一段是裸黑屏——用户在列表已经看过这张图,点开反而先黑
一段)。共用同一份 imageStyle transform + contain,与原图几何完全
一致,原图 onLoad 后本层卸掉,视觉上无跳变。
绝对定位而非参与 flex:与原图同为 flex 子节点会被 Yoga 各分一半高度。
*/}
{layers.showPreview && previewUri ? (
<AnimatedImage
// 垫底图画不出来时必须撤掉并让 spinner 回来,不能停在纯黑(见
// failedPreviewUri)。乐观先渲染而不是等它 onLoad:本地文件解码只要
// 一两帧,为它先挂一帧 spinner 反而每次打开都闪一下,与本次「让用户
// 感知不到」的目标相反。
onError={() => setFailedPreviewUri(previewUri)}
onLoad={(event) => {
const source = event.source;
if (source && source.width > 0 && source.height > 0) {
setPreviewSize({ uri: previewUri, width: source.width, height: source.height });
}
}}
contentFit="contain"
recyclingKey={previewUri}
source={{ uri: previewUri }}
style={[styles.pagePreviewLayer, imageStyle]}
testID="message.imageLightboxPreviewLayer"
/>
) : null}
{uri && !fullFailed ? <AnimatedImage
// 两条失败路径都要接:可重取的图交父层做一次 forceRefresh 自愈(再失败
// 落父层 error 态给重试按钮);直连图在本页落失败态,提供原地重试。
onError={() => {
setFailedFullUri(uri);
setFailedFullMedia(resolveState?.media);
setLoadedUri(null);
if (onImageError && retryable) onImageError(image);
}}
onLoad={(event) => {
// 撤垫底的唯一依据:原图真的有像素了。早于此撤(例如取件一完成
// 就撤)就会把下载窗口裸露成黑屏,正是本次修复的起因。
setLoadedUri(uri);
onImageLoaded(image, resolveState?.status === 'ready' ? resolveState.media : undefined);
const source = event.source;
if (source && source.width > 0 && source.height > 0) {
onNaturalSize(image.key, { width: source.width, height: source.height });
}
}}
contentFit="contain"
recyclingKey={uri}
source={{ uri }}
style={[styles.pageFill, imageStyle]}
/> : null}
{/* 连缩略图都没有(直连 http 图 / 缓存未命中):至少给转圈,不留纯黑无反馈。 */}
{layers.showSpinner ? (
<View pointerEvents="none" style={styles.pageSpinnerLayer}>
<ActivityIndicator color="#ffffff" testID="message.imageLightboxLoading" />
</View>
) : null}
{overlayVisible ? (
// 两遍绘制(先全部白描边、再全部红线):交叉处不会出现白边压
// 红线的断裂感,与桌面 / 烧录一致。
<Animated.View
pointerEvents="none"
style={[
{
height: annotationBase.height,
left: annotationBase.left,
position: 'absolute',
top: annotationBase.top,
width: annotationBase.width,
},
imageStyle,
]}
>
<Svg
height="100%"
viewBox={`0 0 ${naturalSize.width} ${naturalSize.height}`}
width="100%"
>
{committedOutlinePaths}
{draftPathD ? (
<Path
d={draftPathD}
fill="none"
key="outline-draft"
stroke={ANNOTATION_OUTLINE_COLOR}
strokeLinecap="round"
strokeLinejoin="round"
strokeWidth={overlayOutlineWidth}
/>
) : null}
{committedStrokePaths}
{draftPathD ? (
<Path
d={draftPathD}
fill="none"
key="stroke-draft"
stroke={ANNOTATION_STROKE_COLOR}
strokeLinecap="round"
strokeLinejoin="round"
strokeWidth={overlayStrokeWidth}
/>
) : null}
</Svg>
</Animated.View>
) : null}
</Animated.View>
</GestureDetector>
) : (
// 失败分支没有图片手势层:单击空白处同样切换 chrome(关闭按钮在 chrome 里);
// 重试按钮自己消费点击不受影响。
<Pressable
accessible={false}
onPress={onToggleChrome}
style={[styles.pageFill, styles.pageCenter]}
>
<Text style={styles.stateText}>
{t(mediaLoadFailureKey(resolveState?.status === 'error' ? resolveState.error : undefined))}
</Text>
{retryable || fullFailed ? (
<Pressable
accessibilityLabel={t('message.lightbox.retryLoadImage')}
accessibilityRole="button"
onPress={(event) => {
event.stopPropagation();
if (retryable) onRetry(image);
else {
// 清掉失败态后重新挂载 Image,原 URI 原地重试,不改签名 URL。
setFailedFullUri(null);
setLoadedUri(null);
}
}}
style={styles.retryButton}
testID="message.imageLightboxRetryButton"
>
<Text style={styles.retryText}>
{t('message.lightbox.retry')}
</Text>
</Pressable>
) : null}
</Pressable>
)}
{showOriginalNotice ? (
<View pointerEvents="box-none" style={[styles.originalNotice, {
top: insets.top + 64, left: insets.left + 16, right: insets.right + 16,
}]}>
<ErrorNotice
message={t(originalFailed ? 'message.lightbox.originalUnavailable' : 'message.lightbox.loadingOriginal')}
description={originalFailed ? t(mediaLoadFailureKey(resolveState?.status === 'error' ? resolveState.error : undefined)) : undefined}
testID="message.imageLightboxOriginalNotice"
actions={retryable || fullFailed ? (
<ErrorNoticeAction
label={t('message.lightbox.retryOriginal')}
busy={!originalFailed}
disabled={!originalFailed}
onPress={retryOriginal}
testID="message.imageLightboxRetryButton"
/>
) : undefined}
/>
</View>
) : null}
</View>
);
});
/**
* 视频页:系统原生播放器(与文件预览同一组件),无缩放手势;单击交给系统播放
* 控件,chrome 在视频页常驻。只有成为当前页才挂播放器,翻走即卸载停播,不在
* 后台为相邻页起播放器;未激活时显示列表缩略图(若有)作封面。
*/
const LightboxVideoPage = memo(function LightboxVideoPage({
active,
height,
image,
insetBottom,
insetTop,
onRetry,
onToggleChrome,
previewUri,
resolveState,
uri,
width,
}: {
active: boolean;
height: number;
image: MobileMessageGalleryImage;
insetBottom: number;
insetTop: number;
onRetry(image: MobileMessageGalleryImage): void;
onToggleChrome(): void;
previewUri: string | null;
resolveState: PageResolveState | null;
uri: string | null;
width: number;
}) {
const { t } = useTranslation();
/** 原生播放失败的地址(换地址天然失效):退到 WebView 播放器,与文件预览一致。 */
const [nativeFailedUri, setNativeFailedUri] = useState<string | null>(null);
/** WebView 兜底也播不了的地址:落失败态给重试,不能停在黑屏播放器上。 */
const [webFailedUri, setWebFailedUri] = useState<string | null>(null);
const media = image.payload.media;
const retryable = !media.previewable && isDesktopLocalMediaUrl(media.url);
const resolvedUnsupported = resolveState?.status === 'ready' && !resolveState.media.previewable;
const playbackFailed = !!uri && webFailedUri === uri;
const failed = playbackFailed || (!uri && (
resolveState?.status === 'error' || resolvedUnsupported || (!retryable && !media.previewable)
));
const handleNativeError = useCallback(() => {
if (uri) setNativeFailedUri(uri);
}, [uri]);
const handleWebStatus = useCallback((status: MobileMediaPlayerStatus) => {
if (status.state === 'error' && uri) setWebFailedUri(uri);
}, [uri]);
const retry = useCallback(() => {
// 播放失败的标记按地址记:重试先清掉,取件图再 forceRefresh 换新地址;
// 直连地址原地重新挂载原生播放器。
setNativeFailedUri(null);
setWebFailedUri(null);
if (retryable) onRetry(image);
}, [image, onRetry, retryable]);
let body: React.ReactNode;
if (failed) {
body = (
<Pressable accessible={false} onPress={onToggleChrome} style={[styles.pageFill, styles.pageCenter]}>
<Text style={styles.stateText}>
{t(mediaLoadFailureKey(resolveState?.status === 'error' ? resolveState.error : undefined))}
</Text>
{retryable || playbackFailed ? (
<Pressable
accessibilityLabel={t('message.lightbox.retry')}
accessibilityRole="button"
onPress={(event) => {
event.stopPropagation();
retry();
}}
style={styles.retryButton}
testID="message.imageLightboxRetryButton"
>
<Text style={styles.retryText}>{t('message.lightbox.retry')}</Text>
</Pressable>
) : null}
</Pressable>
);
} else if (active && uri) {
body = nativeFailedUri === uri || uri.startsWith('data:') ? (
<RemoteMediaPlayerWebView
kind="video"
mimeType={resolveState?.status === 'ready' ? resolveState.media.mimeType : media.mimeType}
onStatusChange={handleWebStatus}
style={styles.pageFill}
testID="message.imageLightboxVideoWebPlayer"
title={image.title}
url={uri}
visible={active}
/>
) : (
<NativeVideoPlayer
onError={handleNativeError}
testID="message.imageLightboxVideoPlayer"
url={uri}
visible={active}
/>
);
} else {
body = (
<View style={[styles.pageFill, styles.pageCenter]}>
{previewUri ? (
<Image contentFit="contain" source={{ uri: previewUri }} style={StyleSheet.absoluteFill} />
) : null}
{active ? <ActivityIndicator color="#ffffff" testID="message.imageLightboxLoading" /> : null}
</View>
);
}
return (
<View style={{ height, paddingBottom: insetBottom, paddingTop: insetTop, width }} testID="message.imageLightboxVideoPage">
{body}
</View>
);
});
const absoluteFill = { bottom: 0, left: 0, position: 'absolute', right: 0, top: 0 } as const;
const styles = StyleSheet.create({
root: { flex: 1 },
backdrop: { backgroundColor: '#000000', ...absoluteFill },
chrome: { ...absoluteFill, alignItems: 'center' },
closeButton: {
alignItems: 'center',
backgroundColor: 'rgba(0, 0, 0, 0.6)',
borderRadius: radius.pill,
height: 48,
justifyContent: 'center',
left: 16,
position: 'absolute',
width: 48,
},
pageFill: { flex: 1, height: '100%', width: '100%' },
pageCenter: { alignItems: 'center', gap: 16, justifyContent: 'center' },
// 垫底缩略图 / 转圈都脱离 flex 流:与原图同为 flex 子节点会被各分一半高度。
pagePreviewLayer: { ...absoluteFill },
pageSpinnerLayer: { ...absoluteFill, alignItems: 'center', justifyContent: 'center' },
originalNotice: { position: 'absolute' },
pageLabel: {
color: 'rgba(255, 255, 255, 0.85)',
fontSize: typeScale.footnote,
lineHeight: lineHeight.caption,
fontVariant: ['tabular-nums'],
},
fileHeader: {
alignItems: 'center',
flexDirection: 'row',
gap: 12,
paddingHorizontal: 20,
width: '100%',
},
fileHeaderDone: { color: '#ffffff', fontSize: typeScale.bodyLarge, lineHeight: lineHeight.bodyLarge, fontWeight: fontWeight.medium },
fileHeaderTitleCol: { alignItems: 'center', flex: 1, gap: 2, minWidth: 0 },
fileHeaderTitle: { color: '#ffffff', fontSize: typeScale.body, lineHeight: lineHeight.body, fontWeight: fontWeight.semibold },
fileHeaderMeta: { color: 'rgba(255,255,255,0.64)', fontSize: typeScale.caption, lineHeight: lineHeight.caption },
fileHeaderShareSpacer: { width: 20 },
actionBar: {
alignItems: 'center',
paddingHorizontal: 16,
left: 0,
position: 'absolute',
right: 0,
},
// 胶囊底(对齐桌面 LightboxToolbar:黑色半透明 + 白描边 + backdrop 感):
// 按钮不再裸浮在图片上,图片内容再花也不与工具栏图标混叠。
actionBarPill: {
alignItems: 'center',
backgroundColor: 'rgba(0, 0, 0, 0.6)',
borderColor: 'rgba(255, 255, 255, 0.22)',
borderRadius: radius.pill, // 胶囊语义用 pill(RN 截半)
borderWidth: StyleSheet.hairlineWidth,
flexDirection: 'row',
flexWrap: 'wrap',
justifyContent: 'center',
maxWidth: '100%',
gap: 16,
paddingHorizontal: 16,
paddingVertical: 9,
},
actionItem: {
alignItems: 'center',
flexShrink: 1,
gap: 4,
justifyContent: 'center',
minHeight: 48,
minWidth: 48,
},
actionLabel: {
color: 'rgba(255,255,255,0.72)',
fontSize: typeScale.micro,
lineHeight: lineHeight.micro,
textAlign: 'center',
},
actionDivider: {
backgroundColor: 'rgba(255, 255, 255, 0.25)',
height: 22,
width: StyleSheet.hairlineWidth,
},
actionLabelDisabled: { color: DISABLED_ICON_COLOR },
stateText: { color: 'rgba(255, 255, 255, 0.85)', fontSize: typeScale.bodySmall, lineHeight: lineHeight.bodySmall },
retryButton: {
borderColor: 'rgba(255, 255, 255, 0.5)',
borderRadius: radius.pill, // 圆形按钮语义用 pill(胶囊,RN 截半)
borderWidth: StyleSheet.hairlineWidth,
paddingHorizontal: 20,
paddingVertical: 8,
},
retryText: { color: '#ffffff', fontSize: typeScale.bodySmall, lineHeight: lineHeight.bodySmall },
});