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): 稳定上传图片预览并释放附件布局高度

Dash7e1dde8341bf
diff --git a/apps/mobile/app/sessions/[sessionId].tsx b/apps/mobile/app/sessions/[sessionId].tsx
index 2579de90fc..f58f890c58 100644
--- a/apps/mobile/app/sessions/[sessionId].tsx
+++ b/apps/mobile/app/sessions/[sessionId].tsx
@@ -282,6 +282,7 @@ import { RecentPhotosStrip } from '@/session/ContextSheetMediaViews';
import { ContextSheetGoalView, goalStatusLabel } from '@/session/ContextSheetGoalView';
import { parseGoalLimitsRouteParam } from '@/session/goalLimitsRouteParam';
import { ComposerAttachmentCollapsedBadge, ComposerAttachmentTray } from '@/session/ComposerAttachmentTray';
+import { useComposerPendingImagePreview } from '@/session/useComposerPendingImagePreview';
import { useSlowSendVisible, type SlowSendPhase } from '@/session/SlowSendNotice';
import { ComposerActivityPill, composerActivityPillOverlayColor, makeComposerActivityPillStyles } from '@/session/ComposerActivityPill';
import { PlanModeChip } from '@/session/PlanModeChip';
@@ -7209,6 +7210,7 @@ function SessionScreenContent() {
.finally(() => setStopPending(false));
};
+ const pendingImagePreview = useComposerPendingImagePreview({ attachments, previews: attachmentPreviews, pendingUploads, getUploadedAttachmentId });
const renderComposerControls = ({ composerLayout, composerSendUnavailableReason, composerStopDisabledReason, composerStopDisabled, composerShowInlineStop, composerSendSlotIsStop, composerShowSendButton, composerSendDisabled, voiceIsListening, voiceIsProcessing, voiceProcessingIndicator, voiceIsBusy, voiceRecordingTimer, composerVoicePlacement }: SessionComposerControlState): SessionComposerControls => {
composerSendTargetEnabledRef.current = composerShowSendButton && !composerLayout.send.disabled;
if (!composerShowSendButton) sendButtonFrameRef.current = null;
@@ -7419,7 +7421,7 @@ function SessionScreenContent() {
const renderComposerAttachmentTray = () => (
<ComposerAttachmentTray
attachments={attachments}
- getUploadedAttachmentId={getUploadedAttachmentId}
+ onPreviewPending={pendingImagePreview.open}
onPreview={setComposerPreviewAttachmentId}
onRemove={removeRemoteFileAttachment}
onRemovePending={removePendingUpload}
@@ -8945,6 +8947,7 @@ function SessionScreenContent() {
|| (modelSheetOpen && canUseComposer)
|| (permissionSheetOpen && canUseComposer)
|| composerPreviewAttachmentId !== null
+ || pendingImagePreview.active
|| sessionListDrawerOverlayMounted
|| messageBlockingOverlay
);
@@ -10154,6 +10157,7 @@ function SessionScreenContent() {
testID="session.permissionSheet"
/>
) : null}
+ {pendingImagePreview.host}
{composerPreviewUrl && composerGalleryImages.length > 0 ? (
// composer 托盘图片的全屏查看(沿用聊天消息同款 ImageLightbox;本地图无需远端取件)。
// annotation:托盘图可圈点标注 / 再编辑,保存后烧录替换附件重新上传。
diff --git a/apps/mobile/app/sessions/new.tsx b/apps/mobile/app/sessions/new.tsx
index 51f44870e7..542c175089 100644
--- a/apps/mobile/app/sessions/new.tsx
+++ b/apps/mobile/app/sessions/new.tsx
@@ -170,6 +170,7 @@ import { RecentPhotosStrip } from '@/session/ContextSheetMediaViews';
import { ContextSheetGoalCreateForm } from '@/session/ContextSheetGoalView';
import type { MobileGoalLimitsInput } from '@cindy/maker-shared/device-link-contract';
import { ComposerAttachmentCollapsedBadge, ComposerAttachmentTray } from '@/session/ComposerAttachmentTray';
+import { useComposerPendingImagePreview } from '@/session/useComposerPendingImagePreview';
import { SlowSendNotice, type SlowSendPhase } from '@/session/SlowSendNotice';
import { ImageLightbox } from '@/session/ImageLightbox';
import {
@@ -2101,6 +2102,7 @@ export default function NewRemoteSessionScreen() {
draftText: draft.firstMessage,
});
const composerIncomingImageCount = pendingUploads.filter((item) => item.kind === 'image').length + pastePlaceholderCount;
+ const pendingImagePreview = useComposerPendingImagePreview({ attachments, previews: attachmentPreviews, pendingUploads, getUploadedAttachmentId });
const composerImageCount = attachments.filter((item) => item.category === 'image').length + composerIncomingImageCount;
const { active: composerImageHoldActive, collapse: collapseComposerImages } = useComposerImageExpansion(composerImageCount, imageSelectionRevision);
const composerCardActive = firstMessageInputFocused || composerPillOpen.opening
@@ -4623,7 +4625,7 @@ export default function NewRemoteSessionScreen() {
const renderComposerAttachmentTray = () => (
<ComposerAttachmentTray
attachments={attachments}
- getUploadedAttachmentId={getUploadedAttachmentId}
+ onPreviewPending={pendingImagePreview.open}
onPreview={setComposerPreviewAttachmentId}
onRemove={removeAttachment}
onRemovePending={removePendingUpload}
@@ -7274,6 +7276,7 @@ export default function NewRemoteSessionScreen() {
options={runtimeOptions.permissionOptions}
testID="newSession.permissionSheet"
/>
+ {pendingImagePreview.host}
{composerPreviewUrl && composerGalleryImages.length > 0 ? (
// composer 托盘图片的全屏查看(沿用聊天消息同款 ImageLightbox;本地图无需远端取件)。
// annotation:托盘图可圈点标注 / 再编辑,保存后烧录替换附件重新上传。
diff --git a/apps/mobile/src/__tests__/composerAttachmentTrayOverlayColor.test.tsx b/apps/mobile/src/__tests__/composerAttachmentTrayOverlayColor.test.tsx
index a0dcc283d6..2057eeca45 100644
--- a/apps/mobile/src/__tests__/composerAttachmentTrayOverlayColor.test.tsx
+++ b/apps/mobile/src/__tests__/composerAttachmentTrayOverlayColor.test.tsx
@@ -8,12 +8,14 @@ import {
} from "@/session/ComposerAttachmentTray";
import { i18n } from "@/i18n";
import { useComposerImageExpansion } from "@/session/useComposerImageExpansion";
+import { useComposerPendingImagePreview } from "@/session/useComposerPendingImagePreview";
import type { RemoteSerializedAttachment } from "@/session/types";
import type { PendingLocalAttachmentUpload } from "@/session/mobileLocalAttachmentUpload";
const theme = vi.hoisted(() => ({
mode: "light",
files: null as Set<string> | null,
+ mounts: 0,
}));
vi.mock("react-native", async () => {
const { createElement } = await import("react");
@@ -64,21 +66,29 @@ vi.mock("@/components/AppText", async () => ({
}));
vi.mock("@/components/FileTypeIcon", () => ({ FileTypeIcon: () => null }));
vi.mock("expo-image", () => ({ Image: () => null }));
-vi.mock("@/session/ImageLightbox", () => ({
- ImageLightbox: ({
- images,
- onClose,
- }: {
- images: { url: string }[];
- onClose(): void;
- }) => (
- <button data-testid="lightbox" onClick={onClose}>
- {theme.files && !theme.files.has(images[0].url)
- ? "missing"
- : images[0].url}
- </button>
- ),
-}));
+vi.mock("@/session/ImageLightbox", async () => {
+ const { useEffect } = await import("react");
+ return {
+ ImageLightbox: ({
+ images,
+ onClose,
+ }: {
+ images: { url: string }[];
+ onClose(): void;
+ }) => {
+ useEffect(() => {
+ theme.mounts += 1;
+ }, []);
+ return (
+ <button data-testid="lightbox" onClick={onClose}>
+ {theme.files && !theme.files.has(images[0].url)
+ ? "missing"
+ : images[0].url}
+ </button>
+ );
+ },
+ };
+});
vi.mock("lucide-react-native", async () => {
const { createElement } = await import("react");
const icon =
@@ -103,6 +113,7 @@ let root: Root;
let host: HTMLDivElement;
beforeEach(async () => {
theme.files = null;
+ theme.mounts = 0;
Object.assign(globalThis, { IS_REACT_ACT_ENVIRONMENT: true });
await i18n.changeLanguage("zh-CN");
host = document.createElement("div");
@@ -199,19 +210,45 @@ describe("composer attachment tray overlay foreground", () => {
// 上传中图片验证真实托盘打开本地预览,并在上传完成后仍保持查看器。
it("switches an open preview to the durable URI when the temporary file is deleted", () => {
theme.files = new Set(["file:///uploading.jpg"]);
- const render = (uploading: boolean, delivered = false) =>
+ function Composer({
+ uploading,
+ delivered,
+ showTray,
+ }: {
+ uploading: boolean;
+ delivered: boolean;
+ showTray: boolean;
+ }) {
+ const props = {
+ attachments: delivered ? [attachment("done")] : [],
+ previews: { done: "file:///durable.jpg" },
+ pendingUploads: uploading ? [pending("uploading")] : [],
+ getUploadedAttachmentId: (id: string) =>
+ delivered && id === "uploading" ? "done" : undefined,
+ };
+ const preview = useComposerPendingImagePreview(props);
+ return (
+ <>
+ {showTray && (
+ <ComposerAttachmentTray
+ {...props}
+ onPreviewPending={preview.open}
+ onRemove={() => {}}
+ onPreview={() => {}}
+ testIDPrefix="t"
+ />
+ )}
+ {preview.host}
+ </>
+ );
+ }
+ const render = (uploading: boolean, delivered = false, showTray = true) =>
act(() =>
root.render(
- <ComposerAttachmentTray
- attachments={delivered ? [attachment("done")] : []}
- previews={{ done: "file:///durable.jpg" }}
- getUploadedAttachmentId={(id) =>
- delivered && id === "uploading" ? "done" : undefined
- }
- onRemove={() => {}}
- onPreview={() => {}}
- pendingUploads={uploading ? [pending("uploading")] : []}
- testIDPrefix="t"
+ <Composer
+ uploading={uploading}
+ delivered={delivered}
+ showTray={showTray}
/>,
),
);
@@ -224,17 +261,22 @@ describe("composer attachment tray overlay foreground", () => {
expect(host.querySelector('[data-testid="lightbox"]')?.textContent).toBe(
"file:///uploading.jpg",
);
+ render(true, false, false); // Keyboard blur unmounts the attachment tray.
+ expect(host.querySelector('[data-testid="lightbox"]')?.textContent).toBe(
+ "file:///uploading.jpg",
+ );
theme.files.delete("file:///uploading.jpg");
theme.files.add("file:///durable.jpg");
// onUploaded publishes the delivered attachment before the controller removes pending.
- render(true, true);
+ render(true, true, false);
expect(host.querySelector('[data-testid="lightbox"]')?.textContent).toBe(
"file:///durable.jpg",
);
- render(false, true);
+ render(false, true, false);
expect(host.querySelector('[data-testid="lightbox"]')?.textContent).toBe(
"file:///durable.jpg",
);
+ expect(theme.mounts).toBe(1); // No native modal dismissal/presentation race.
act(() =>
host
.querySelector<HTMLButtonElement>('[data-testid="lightbox"]')!
@@ -253,6 +295,7 @@ describe("composer attachment tray overlay foreground", () => {
previews={{}}
onRemove={() => {}}
onPreview={() => {}}
+ onPreviewPending={() => {}}
pendingUploads={[
{ ...pending("unresolved"), previewUri: "" },
pending("failed", true),
@@ -302,6 +345,7 @@ describe("composer attachment tray overlay foreground", () => {
previews={{}}
onRemove={() => {}}
onPreview={() => {}}
+ onPreviewPending={() => {}}
pendingUploads={[pending("uploading"), pending("failed", true)]}
testIDPrefix="t"
/>
diff --git a/apps/mobile/src/__tests__/composerToolbarViewport.test.tsx b/apps/mobile/src/__tests__/composerToolbarViewport.test.tsx
index 11b6b46e50..67319345da 100644
--- a/apps/mobile/src/__tests__/composerToolbarViewport.test.tsx
+++ b/apps/mobile/src/__tests__/composerToolbarViewport.test.tsx
@@ -3,12 +3,19 @@ import React, { act, type ReactNode } from 'react';
import { createRoot } from 'react-dom/client';
import { expect, it, vi } from 'vitest';
import { MobileComposerInputRow } from '@/session/MobileComposerInputRow';
+import type { SharedValue } from 'react-native-reanimated';
+
+const nativeLayout = vi.hoisted(() => new WeakMap<Element, (height: number) => void>());
vi.mock('expo-constants', () => ({ default: { executionEnvironment: 'bare' }, ExecutionEnvironment: { StoreClient: 'storeClient' } }));
vi.mock('react-native', async () => {
const React = await import('react');
- const View = ({ children, testID }: { children?: ReactNode; testID?: string }) =>
- React.createElement('div', { 'data-testid': testID }, children);
+ const flatten = (style: unknown): Record<string, unknown> => Array.isArray(style)
+ ? Object.assign({}, ...style.map(flatten)) : style && typeof style === 'object' ? style as Record<string, unknown> : {};
+ const View = ({ children, testID, style, onLayout }: { children?: ReactNode; testID?: string; style?: unknown; onLayout?: (event: unknown) => void }) =>
+ React.createElement('div', { 'data-testid': testID, style: flatten(style), ref: (node: HTMLDivElement | null) => {
+ if (node && onLayout) nativeLayout.set(node, height => onLayout({ nativeEvent: { layout: { height } } }));
+ } }, children);
const ScrollView = ({ children, testID, scrollEnabled }: { children?: ReactNode; testID?: string; scrollEnabled?: boolean }) =>
React.createElement('div', { 'data-testid': testID, 'data-scroll': String(scrollEnabled) }, children);
return { View, ScrollView, Pressable: View, Platform: { OS: 'ios' },
@@ -66,3 +73,61 @@ it('keeps send/voice/grabber outside the scrolling body and retains the editor a
expect(body.getAttribute('data-scroll')).toBe('true');
} finally { act(() => root.unmount()); }
});
+
+// PR #6291: removing the last attachment left its measured height behind. The
+// existing viewport test covers tree placement, not measurements during a drag.
+it("releases attachment height after deletion and remeasures before the next drag", () => {
+ const container = document.createElement("div");
+ const root = createRoot(container);
+ const progress = { value: 0 } as SharedValue<number>;
+ const render = (hasImage: boolean, inputHeight = 40) =>
+ act(() =>
+ root.render(
+ <MobileComposerInputRow
+ accessibilityLabel="Message"
+ inputTestID="input"
+ placeholder="Message"
+ placeholderTextColor="inherit"
+ value=""
+ onChangeText={() => {}}
+ cardActive
+ collapseProgress={progress}
+ inputFrameHeight={inputHeight}
+ inputElement={<textarea />}
+ accessoryAbove={
+ <>{hasImage ? <div data-testid="attachment">Image</div> : null}</>
+ }
+ testID="composer"
+ />,
+ ),
+ );
+ try {
+ render(true);
+ const measured = container.querySelector(
+ '[data-testid="attachment"]',
+ )!.parentElement!;
+ const folding = measured.parentElement!;
+ act(() => nativeLayout.get(measured)!(80));
+ progress.value = 0.5;
+ render(true, 120);
+ expect(folding.style.height).toBe("40px");
+ expect(
+ container.querySelector("textarea")!.parentElement!.style.height,
+ ).toBe("120px");
+ progress.value = 0;
+ render(false);
+ expect(folding.style.height).toBe("auto");
+ act(() => nativeLayout.get(measured)!(0));
+ progress.value = 0.5;
+ render(false);
+ expect(folding.style.height).toBe("0px");
+ progress.value = 0;
+ render(true);
+ act(() => nativeLayout.get(measured)!(100));
+ progress.value = 0.5;
+ render(true);
+ expect(folding.style.height).toBe("50px");
+ } finally {
+ act(() => root.unmount());
+ }
+});
diff --git a/apps/mobile/src/session/BotGroupComposer.tsx b/apps/mobile/src/session/BotGroupComposer.tsx
index 27971f55c0..41b32318a3 100644
--- a/apps/mobile/src/session/BotGroupComposer.tsx
+++ b/apps/mobile/src/session/BotGroupComposer.tsx
@@ -43,6 +43,7 @@ import { BOT_GROUP_STEP_AVATAR_SIZE, BotGroupAvatar } from './BotGroupAvatars';
import { BotGroupMenu } from './BotGroupMenu';
import type { BotGroupIdentityLookup } from './BotGroupPlan';
import { ComposerAttachmentCollapsedBadge, ComposerAttachmentTray } from './ComposerAttachmentTray';
+import { useComposerPendingImagePreview } from './useComposerPendingImagePreview';
import { ContextSheet, ContextSheetGroup, ContextSheetRow } from './ContextSheet';
import { RecentPhotosStrip } from './ContextSheetMediaViews';
import { ImageLightbox } from './ImageLightbox';
@@ -112,6 +113,7 @@ export function BotGroupComposer({
deviceId,
onPicked: () => { setSheetOpen(false); focusInput(); },
});
+ const pendingImagePreview = useComposerPendingImagePreview(tray);
const attachmentsEnabled = attachmentsSupported && online;
// Paste handlers stay mounted for the whole screen (the input would remount otherwise); they
// check support when an image actually arrives.
@@ -351,7 +353,7 @@ export function BotGroupComposer({
onPasteImagesLoadFailed={() => { if (pasteAllowedRef.current) tray.failPastePlaceholders(); }}
cardActive={cardActive}
accessoryAbove={hasAttachments ? <ComposerAttachmentTray attachments={tray.attachments} previews={tray.previews}
- getUploadedAttachmentId={tray.getUploadedAttachmentId}
+ onPreviewPending={pendingImagePreview.open}
pendingUploads={tray.pendingUploads} pastePlaceholderCount={tray.pastePlaceholderCount}
onPreview={setPreviewId} onRemove={tray.removeAttachment} onRemovePending={tray.removePendingUpload}
onRetryPending={tray.retryPendingUpload} removeDisabled={sending} testIDPrefix="botGroup" /> : null}
@@ -396,6 +398,7 @@ export function BotGroupComposer({
onPress={() => { setDivision(true); inputRef.current?.focus(); }} testID="botGroup.contextSheetDivisionRow" />
</ContextSheetGroup>
</ContextSheet>
+ {pendingImagePreview.host}
{previewUrl ? <ImageLightbox images={tray.galleryImages} initialUrl={previewUrl} onClose={() => setPreviewId(null)} /> : null}
</View>;
}
diff --git a/apps/mobile/src/session/ComposerAttachmentTray.tsx b/apps/mobile/src/session/ComposerAttachmentTray.tsx
index f180432f68..d32a5fdcb4 100644
--- a/apps/mobile/src/session/ComposerAttachmentTray.tsx
+++ b/apps/mobile/src/session/ComposerAttachmentTray.tsx
@@ -12,16 +12,12 @@ import { FileTypeIcon } from '@/components/FileTypeIcon';
*/
import { Pen, RefreshCw, X } from 'lucide-react-native';
import { Image } from 'expo-image';
-import { useMemo, useState } from 'react';
import { useTranslation } from 'react-i18next';
import { ActivityIndicator, Pressable, StyleSheet, View } from 'react-native';
import { Text } from '@/components/AppText';
import type { RemoteSerializedAttachment } from '@/session/types';
import type { PendingLocalAttachmentUpload } from '@/session/mobileLocalAttachmentUpload';
import { attachmentDisplayLabel, pendingUploadDisplayLabel } from '@/session/attachments';
-import { ImageLightbox } from '@/session/ImageLightbox';
-import { buildMediaPayload } from '@/session/messagePayload';
-import type { MobileMessageGalleryImage } from '@/session/messageGallery';
import { fontWeight, iconSize, iconStroke, lineHeight, radius, spacing, typeScale, useTheme, useThemedStyles, type ThemeColors } from '@/theme';
/** 输入卡内的缩略图为正方形(产品决策,不用横长方)。 */
@@ -36,7 +32,8 @@ export interface ComposerAttachmentTrayProps {
onPreview: (attachmentId: string) => void;
/** 乐观上传中的本机附件(图片=缩略卡,文件=chip,均带转圈;失败态带重试)。 */
pendingUploads?: readonly PendingLocalAttachmentUpload[];
- getUploadedAttachmentId?: (localId: string) => string | undefined;
+ /** Screen owns the viewer so keyboard blur cannot unmount it with this tray. */
+ onPreviewPending: (localId: string) => void;
/** X 一个上传中的附件(取消上传)。 */
onRemovePending?: (localId: string) => void;
/** 重试一个失败态的上传卡。 */
@@ -58,7 +55,7 @@ export function ComposerAttachmentTray({
onRemove,
onPreview,
pendingUploads = [],
- getUploadedAttachmentId,
+ onPreviewPending,
onRemovePending,
onRetryPending,
pastePlaceholderCount = 0,
@@ -69,19 +66,6 @@ export function ComposerAttachmentTray({
const { t } = useTranslation();
const styles = useThemedStyles(makeTrayStyles);
const { colors } = useTheme();
- const [pendingPreviewId, setPendingPreviewId] = useState<string | null>(null);
- const deliveredId = pendingPreviewId ? getUploadedAttachmentId?.(pendingPreviewId) : undefined;
- const delivered = attachments.find((item) => item.id === deliveredId);
- const pending = pendingUploads.find((item) => item.localId === pendingPreviewId);
- // Prefer the delivered URI even during the brief overlap of both lists: the
- // uploader may already have deleted the temporary source at this point.
- const previewUri = delivered ? previews[delivered.id] : pending?.previewUri;
- const previewName = delivered?.name ?? pending?.name;
- const pendingPreview = useMemo<MobileMessageGalleryImage[]>(() => {
- if (!previewUri || !previewName || !pendingPreviewId) return [];
- const payload = buildMediaPayload({ kind: 'image', previewable: true, title: previewName, url: previewUri }, previewName);
- return payload.kind === 'media' ? [{ key: pendingPreviewId, payload, title: previewName, url: previewUri }] : [];
- }, [previewUri, previewName, pendingPreviewId]);
if (attachments.length === 0 && pendingUploads.length === 0 && pastePlaceholderCount === 0) return null;
return (
<View style={styles.tray} testID={`${testIDPrefix}.attachmentTray`}>
@@ -167,7 +151,7 @@ export function ComposerAttachmentTray({
accessibilityLabel={t('composer.attachments.viewImage', { name: pending.name })}
accessibilityRole="button"
disabled={!pending.previewUri}
- onPress={() => setPendingPreviewId(pending.localId)}
+ onPress={() => onPreviewPending(pending.localId)}
style={({ pressed }) => [styles.thumbBusyOverlay, pressed && styles.pressed]}
testID={`${testIDPrefix}.attachmentPendingPreviewButton`}
>
@@ -236,9 +220,6 @@ export function ComposerAttachmentTray({
</View>
</View>
))}
- {pendingPreview.length > 0 ? (
- <ImageLightbox key={previewUri} images={pendingPreview} initialUrl={pendingPreview[0].url} onClose={() => setPendingPreviewId(null)} />
- ) : null}
</View>
);
}
diff --git a/apps/mobile/src/session/MobileComposerInputRow.tsx b/apps/mobile/src/session/MobileComposerInputRow.tsx
index 6009e803d5..e23782e7ca 100644
--- a/apps/mobile/src/session/MobileComposerInputRow.tsx
+++ b/apps/mobile/src/session/MobileComposerInputRow.tsx
@@ -504,7 +504,7 @@ function ComposerFoldingSection({ progress, children }: { progress?: SharedValue
const style = useAnimatedStyle(() => {
const amount = progress?.value ?? 0;
return {
- height: measuredHeight.value > 0 ? measuredHeight.value * (1 - amount) : 'auto' as const,
+ height: amount > 0 ? measuredHeight.value * (1 - amount) : 'auto' as const,
opacity: 1 - amount,
overflow: 'hidden' as const,
flexShrink: 0,
@@ -514,7 +514,7 @@ function ComposerFoldingSection({ progress, children }: { progress?: SharedValue
<View style={{ flexShrink: 0 }} onLayout={event => {
// Never feed an animated/constrained measurement back into its own height.
// Keep the natural expanded size until the gesture has fully reversed.
- if ((progress?.value ?? 0) === 0 && event.nativeEvent.layout.height > 0) {
+ if ((progress?.value ?? 0) === 0) {
measuredHeight.value = event.nativeEvent.layout.height;
}
}}>
@@ -751,8 +751,10 @@ const makeMobileComposerInputRowStyles = (colors: ThemeColors) => ({
flexDirection: 'row',
minWidth: 0,
},
- bodyScroll: { flexShrink: 1 },
- bodyScrollContent: { flexGrow: 1 },
+ // Size the viewport to its current children. ScrollView's default flexGrow=1
+ // otherwise keeps the old attachment height and absorbs input resize changes.
+ bodyScroll: { flexGrow: 0, flexShrink: 1 },
+ bodyScrollContent: { flexGrow: 0 },
toolbarRow: {
alignItems: 'center',
flexDirection: 'row',
diff --git a/apps/mobile/src/session/useComposerPendingImagePreview.tsx b/apps/mobile/src/session/useComposerPendingImagePreview.tsx
new file mode 100644
index 0000000000..e3ab591598
--- /dev/null
+++ b/apps/mobile/src/session/useComposerPendingImagePreview.tsx
@@ -0,0 +1,49 @@
+import { useMemo, useState } from "react";
+import { ImageLightbox } from "./ImageLightbox";
+import { buildMediaPayload } from "./messagePayload";
+import type { MobileMessageGalleryImage } from "./messageGallery";
+import type { ComposerAttachmentTrayProps } from "./ComposerAttachmentTray";
+
+/** Keep the viewer at screen level: the tray unmounts when the keyboard blurs. */
+export function useComposerPendingImagePreview({
+ attachments,
+ previews,
+ pendingUploads = [],
+ getUploadedAttachmentId,
+}: Pick<
+ ComposerAttachmentTrayProps,
+ "attachments" | "previews" | "pendingUploads"
+> & {
+ getUploadedAttachmentId: (localId: string) => string | undefined;
+}) {
+ const [localId, setLocalId] = useState<string | null>(null);
+ const deliveredId = localId ? getUploadedAttachmentId(localId) : undefined;
+ const delivered = attachments.find((item) => item.id === deliveredId);
+ const pending = pendingUploads.find((item) => item.localId === localId);
+ const uri = delivered ? previews[delivered.id] : pending?.previewUri;
+ const name = delivered?.name ?? pending?.name;
+ const images = useMemo<MobileMessageGalleryImage[]>(() => {
+ if (!uri || !name || !localId) return [];
+ const payload = buildMediaPayload(
+ { kind: "image", previewable: true, title: name, url: uri },
+ name,
+ );
+ return payload.kind === "media"
+ ? [{ key: localId, payload, title: name, url: uri }]
+ : [];
+ }, [uri, name, localId]);
+ return {
+ open: setLocalId,
+ active: images.length > 0,
+ // The lightbox follows the stable image key when the uploader replaces its URI.
+ host:
+ images.length > 0 ? (
+ <ImageLightbox
+ images={images}
+ initialUrl={images[0].url}
+ initialImageKey={localId ?? undefined}
+ onClose={() => setLocalId(null)}
+ />
+ ) : null,
+ };
+}