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): 统一待发送与正式消息的附件布局 (#4069)

Dashb57c5eefb1c1
diff --git a/apps/mobile/src/__tests__/messageMediaThumbnailWiring.test.ts b/apps/mobile/src/__tests__/messageMediaThumbnailWiring.test.ts
index 17198fe5d9..e553c23472 100644
--- a/apps/mobile/src/__tests__/messageMediaThumbnailWiring.test.ts
+++ b/apps/mobile/src/__tests__/messageMediaThumbnailWiring.test.ts
@@ -66,6 +66,34 @@ describe('mobile message media thumbnail wiring', () => {
expect(mediaPreview).not.toContain('mediaCaption');
});
+ it('uses delivered media and file renderers above the pending text bubble', () => {
+ const pending = readTextLf(resolve(process.cwd(), 'src/session/PendingSendBubble.tsx'), 'utf8');
+ const pendingBranch = rendererSource.slice(
+ rendererSource.indexOf("case 'pending_send':"),
+ rendererSource.indexOf('const RenderListItemView'),
+ );
+ expect(pendingBranch).toContain('<PendingAttachmentImage');
+ expect(pendingBranch).not.toContain('previewable: true');
+ const pendingImage = rendererSource.slice(
+ rendererSource.indexOf('function PendingAttachmentImage'),
+ rendererSource.indexOf('function MediaPreview'),
+ );
+ // iOS ph:// 必须沿用相册托盘的 Expo 解码器,并从加载结果量尺寸。
+ expect(rendererSource).toContain("import { Image as ExpoImage } from 'expo-image'");
+ expect(pendingImage).toContain('<ExpoImage');
+ expect(pendingImage).toContain('contentFit="contain"');
+ expect(pendingImage).toContain('source: { width, height }');
+ expect(pendingImage).toContain('attachmentImageDisplaySize');
+ expect(pendingImage).toContain('styles.attachmentImageWrap');
+ expect(pendingImage).not.toContain('Image.getSize');
+ expect(pendingBranch).toContain('<FileChip');
+ expect(pendingBranch).toContain('<MarkdownBody');
+ expect(pending.indexOf('<AttachmentThumbStrip')).toBeLessThan(pending.indexOf('{hasBody ?'));
+ expect(pending).toContain('item.fileNames.map(renderFile)');
+ expect(pending).not.toContain('height: 72');
+ expect(pending).not.toContain('contentFit="cover"');
+ });
+
it('exempts images from close-time release in the payload viewer', () => {
expect(rendererSource).toContain("remoteMedia.kind !== 'image'");
// 查看器取件插队头;重试按钮显式 forceRefresh 穿透负缓存(挂载取件不传)
diff --git a/apps/mobile/src/__tests__/mobileLocalAttachmentUpload.test.ts b/apps/mobile/src/__tests__/mobileLocalAttachmentUpload.test.ts
index f4c39a4673..6718c80fa2 100644
--- a/apps/mobile/src/__tests__/mobileLocalAttachmentUpload.test.ts
+++ b/apps/mobile/src/__tests__/mobileLocalAttachmentUpload.test.ts
@@ -659,6 +659,7 @@ describe('claim(划归乐观消息)', () => {
failed: false,
kind: 'image',
previewUri: 'file:///tmp/a.jpg',
+ name: 'a.jpg',
}]);
controller.claim(claimable.map((task) => task.localId));
// 托盘同步清空,限额与发送等待不再计入。
@@ -748,6 +749,7 @@ describe('claim(划归乐观消息)', () => {
failed: true,
kind: 'image',
previewUri: 'file:///tmp/a.jpg',
+ name: 'a.jpg',
}]);
const snapshotCount = pendingSnapshots.length;
diff --git a/apps/mobile/src/__tests__/pendingSendItems.test.ts b/apps/mobile/src/__tests__/pendingSendItems.test.ts
index 67c2c7d108..e26be794f6 100644
--- a/apps/mobile/src/__tests__/pendingSendItems.test.ts
+++ b/apps/mobile/src/__tests__/pendingSendItems.test.ts
@@ -233,14 +233,23 @@ describe('pending_send 渲染接线', () => {
).replace(/\r\n/g, '\n');
expect(bubbleSource).toContain('<SentInlineAtomBody');
expect(bubbleSource).toContain('interactiveAtoms={false}');
- expect(bubbleSource).toContain('maxVisibleLines={selected ? undefined : 6}');
- // 徽标与正文必须属于同一个 Pressable,点击用户直觉中的左侧状态图标也能展开条目。
- const bubblePressableStart = bubbleSource.indexOf('<Pressable\n accessibilityHint={item.hint');
- const bubblePressableEnd = bubbleSource.indexOf('\n </Pressable>', bubblePressableStart);
- const bubblePressable = bubbleSource.slice(bubblePressableStart, bubblePressableEnd);
- expect(bubblePressableStart).toBeGreaterThan(-1);
- expect(bubbleSource.indexOf('testID={`pendingSend.badge.${item.phase}`}')).toBeLessThan(bubblePressableStart);
- expect(bubblePressable).toContain('hitSlop={{ left: iconSize.xl + spacing.sm }}');
+ expect(bubbleSource).toContain('maxVisibleLines={collapsedLines}');
+ expect(bubbleSource).toContain('LONG_USER_MESSAGE_COLLAPSED_LINES');
+ // 队列操作仅由状态徽标承接,Markdown 横向滚动不嵌套在 Pressable 中。
+ const badgeStart = bubbleSource.indexOf('<Pressable\n accessibilityHint={item.hint');
+ const badgeEnd = bubbleSource.indexOf('\n </Pressable>', badgeStart);
+ expect(badgeStart).toBeGreaterThan(-1);
+ const badge = bubbleSource.slice(badgeStart, badgeEnd);
+ expect(badge).toContain('testID={`pendingSend.badge.${item.phase}`}');
+ expect(badge).toContain('actions.onSelect(selected ? null : item.clientId)');
+ expect(badge).not.toContain('renderText(');
+ expect(badge).toContain('badgePosition');
+ expect(bubbleSource).toContain('event.nativeEvent.layout.x - 28 - spacing.sm');
+ expect(bubbleSource).toContain('onLayout={hasAttachments ? undefined : measureBadgeAnchor}');
+ expect(bubbleSource.indexOf('testID={`pendingSend.bubble.${item.clientId}`}')).toBeGreaterThan(badgeEnd);
+ expect(bubbleSource).toContain('const collapseLatched = collapseLatchBody === displayBody;');
+ expect(bubbleSource).toContain('if (collapseResolved && !collapseLatched) setCollapseLatchBody(displayBody);');
+ expect(bubbleSource).toContain('(measureBody && collapseLatched) || collapseResolved');
const actionPillStart = bubbleSource.indexOf(' actionPill: {');
const actionPillEnd = bubbleSource.indexOf('\n },', actionPillStart);
const actionPillStyle = bubbleSource.slice(actionPillStart, actionPillEnd);
diff --git a/apps/mobile/src/__tests__/sessionOutbox.test.ts b/apps/mobile/src/__tests__/sessionOutbox.test.ts
index db3115e96e..538da16960 100644
--- a/apps/mobile/src/__tests__/sessionOutbox.test.ts
+++ b/apps/mobile/src/__tests__/sessionOutbox.test.ts
@@ -404,7 +404,7 @@ describe('outboxDisplayItem', () => {
readyPreviews: ['file:///tmp/ready-preview.jpg'],
claimedUploads: [
{ localId: 'u-img', failed: false, kind: 'image', previewUri: 'file:///tmp/pending.jpg' },
- { localId: 'u-pdf', failed: false, kind: 'file', previewUri: 'file:///tmp/scan.pdf' },
+ { localId: 'u-pdf', failed: false, kind: 'file', previewUri: 'file:///tmp/scan.pdf', name: 'scan.pdf' },
],
});
let display = outboxDisplayItem(item);
@@ -419,6 +419,7 @@ describe('outboxDisplayItem', () => {
{ key: 'c-1-slot-1', uri: 'file:///tmp/pending.jpg', ossRef: null, uploading: true },
]);
expect(display.fileCount).toBe(1);
+ expect(display.fileNames).toEqual(['scan.pdf']);
// 上传落定后:uploading 归零,ossRef 补上,本地预览保留(第一帧到落定零跳变)。
item = outboxItemWithUpload(item, 'u-img', attachmentFor('landed.jpg'));
display = outboxDisplayItem(item);
diff --git a/apps/mobile/src/session/MessageRenderer.tsx b/apps/mobile/src/session/MessageRenderer.tsx
index b5bd08c32e..b5606d7a2f 100644
--- a/apps/mobile/src/session/MessageRenderer.tsx
+++ b/apps/mobile/src/session/MessageRenderer.tsx
@@ -1,6 +1,7 @@
import { CompanionMessageCard } from '@/session/CompanionMessageCard';
import { createContext, Fragment, memo, useCallback, useContext, useEffect, useLayoutEffect, useMemo, useRef, useState, type ComponentProps, type ReactNode } from 'react';
import { useTranslation } from 'react-i18next';
+import { Image as ExpoImage } from 'expo-image';
import {
ArrowLeftRight,
ArrowUp,
@@ -2663,6 +2664,27 @@ const RenderItemView = memo(function RenderItemView({
<PendingSendBubble
actions={actions.pendingSend}
item={item}
+ screenWidth={actions.screenWidth}
+ renderImage={(uri) => uri ? (
+ <PendingAttachmentImage key={uri}
+ layout={buildMessageContentLayout({ screenWidth: actions.screenWidth })}
+ uri={uri}
+ />
+ ) : (
+ <View style={[styles.attachmentImagePending, {
+ width: buildMessageContentLayout({ screenWidth: actions.screenWidth }).attachmentImageMaxWidth,
+ height: buildMessageContentLayout({ screenWidth: actions.screenWidth }).attachmentImageMaxHeight,
+ }]} />
+ )}
+ renderFile={(name, index) => (
+ <FileChip key={`${name}:${index}`} name={name} presentationOnly
+ layout={buildMessageContentLayout({ screenWidth: actions.screenWidth })} />
+ )}
+ renderText={(text, index) => (
+ <MarkdownBody key={`text:${index}`} text={text} streaming={false}
+ selectable={false} pinContentWidth={false}
+ layout={buildMessageContentLayout({ screenWidth: actions.screenWidth })} />
+ )}
resolveRemoteMedia={actions.onResolveRemoteMedia}
/>
)
@@ -5797,6 +5819,36 @@ function ToolMediaBlock({
const attachmentIntrinsicSizeCache = new Map<string, AttachmentImageIntrinsicSize>();
const ATTACHMENT_INTRINSIC_CACHE_MAX = 500;
+// 相册候选仍可能是 ph://,必须由 expo-image 加载;只复用正式附件的布局,
+// 不把本地相册地址声明为 RN Image / 远端查看器可直接预览的媒体。
+function PendingAttachmentImage({ layout, uri }: { layout: MessageContentLayout; uri: string }) {
+ const styles = useThemedStyles(makeStyles);
+ const [intrinsicSize, setIntrinsicSize] = useRecyclingState<AttachmentImageIntrinsicSize | null>(
+ () => attachmentIntrinsicSizeCache.get(uri) ?? null,
+ );
+ const displaySize = attachmentImageDisplaySize(
+ intrinsicSize, layout.attachmentImageMaxWidth, layout.attachmentImageMaxHeight,
+ );
+ return (
+ <View style={styles.attachmentImageWrap}>
+ <ExpoImage
+ source={{ uri }}
+ recyclingKey={uri}
+ contentFit="contain"
+ onLoad={({ source: { width, height } }) => {
+ if (!(width > 0 && height > 0)) return;
+ if (attachmentIntrinsicSizeCache.size >= ATTACHMENT_INTRINSIC_CACHE_MAX) {
+ attachmentIntrinsicSizeCache.clear();
+ }
+ attachmentIntrinsicSizeCache.set(uri, { width, height });
+ setIntrinsicSize({ width, height });
+ }}
+ style={[styles.attachmentImage, displaySize]}
+ />
+ </View>
+ );
+}
+
/**
* MediaPreview — 聊天列表里的媒体缩略图 / 占位卡片。
* 图片:可直接预览的(http/data:)直接渲染缩略图;桌面端媒体(xdt-image://)mount 时
@@ -5816,6 +5868,7 @@ function MediaPreview({
onOpen,
onResolveRemoteMedia,
variant = 'card',
+ presentationOnly = false,
}: {
layout: MessageContentLayout;
media: NormalizedToolMedia;
@@ -5823,6 +5876,7 @@ function MediaPreview({
onOpen?: () => void;
onResolveRemoteMedia?: ResolveRemoteMediaFn;
variant?: 'card' | 'attachment';
+ presentationOnly?: boolean;
}) {
const styles = useThemedStyles(makeStyles);
const preview = summarizeMessagePayloadPreview(buildMediaPayload(media, label));
@@ -5914,6 +5968,7 @@ function MediaPreview({
);
return (
<MessageContentOpenButton
+ presentationOnly={presentationOnly}
accessibilityLabel={`${preview.actionLabel} ${preview.title}`}
onPress={onOpen}
style={styles.attachmentImageWrap}
@@ -5952,6 +6007,7 @@ function MediaPreview({
const frameSize = { height: layout.imagePreviewHeight, width: layout.imagePreviewWidth };
return (
<MessageContentOpenButton
+ presentationOnly={presentationOnly}
accessibilityLabel={`${preview.actionLabel} ${preview.title}`}
onPress={onOpen}
style={[
@@ -5984,6 +6040,7 @@ function MediaPreview({
return (
<MessageContentOpenButton
+ presentationOnly={presentationOnly}
accessibilityLabel={`${preview.actionLabel} ${preview.title}`}
onPress={onOpen}
style={[
@@ -6035,17 +6092,20 @@ function FileChip({
name,
onOpen,
path,
+ presentationOnly = false,
}: {
layout: MessageContentLayout;
name: string;
onOpen?: () => void;
path?: string;
+ presentationOnly?: boolean;
}) {
const { colors } = useTheme();
const styles = useThemedStyles(makeStyles);
const preview = summarizeMessagePayloadPreview(buildFilePayload(name, path ?? ''));
return (
<MessageContentOpenButton
+ presentationOnly={presentationOnly}
accessibilityLabel={`${preview.actionLabel} ${name}`}
onPress={onOpen}
style={[
@@ -6156,6 +6216,7 @@ function MessageContentOpenButton({
accessibilityLabel,
children,
disabled = false,
+ presentationOnly = false,
onPress,
style,
testID,
@@ -6163,12 +6224,14 @@ function MessageContentOpenButton({
accessibilityLabel: string;
children: ReactNode;
disabled?: boolean;
+ presentationOnly?: boolean;
onPress?: () => void;
style?: StyleProp<ViewStyle>;
testID?: string;
}) {
const styles = useThemedStyles(makeStyles);
const interactionDisabled = disabled || !onPress;
+ if (presentationOnly) return <View style={style} testID={testID}>{children}</View>;
return (
<Pressable
accessibilityLabel={accessibilityLabel}
diff --git a/apps/mobile/src/session/PendingSendBubble.tsx b/apps/mobile/src/session/PendingSendBubble.tsx
index f1e67cbe50..bc5eb30c77 100644
--- a/apps/mobile/src/session/PendingSendBubble.tsx
+++ b/apps/mobile/src/session/PendingSendBubble.tsx
@@ -10,11 +10,14 @@
* - ⚠ = 失败,可重试 / 删除。
* 「排入队尾」是个事实断言,未确认时画它就是谎报,所以未确认一律转圈。
*/
-import { useEffect, useLayoutEffect, useRef, useState } from 'react';
+import { useEffect, useLayoutEffect, useRef, useState, type ReactNode } from 'react';
import { useTranslation } from 'react-i18next';
-import { ActivityIndicator, Pressable, StyleSheet, View } from 'react-native';
-import { Image } from 'expo-image';
+import { ActivityIndicator, Pressable, StyleSheet, View, type LayoutChangeEvent } from 'react-native';
import { Text } from '@/components/AppText';
+import { buildMessageContentLayout } from '@/session/messageContentLayout';
+import { summarizeMessageBubblePresentation } from '@/session/messagePresentation';
+import { LONG_USER_MESSAGE_COLLAPSED_LINES, LONG_USER_MESSAGE_VISUAL_LINE_THRESHOLD, mayExceedVisualLineThreshold, resolveUserMessageCollapse } from '@/session/userMessageCollapse';
+import { sentInlineTokensDisplayText } from '@/session/sentMessageAtoms';
import { SentInlineAtomBody } from '@/session/SentInlineAtomBody';
import {
AlertCircle,
@@ -64,7 +67,7 @@ export interface PendingSendBubbleActions {
}
/**
- * 气泡内图片缩略条:乐观语义下图片从第一帧就以图的形态出现,不做「📎 附件行 → 正式消息
+ * 气泡上方图片附件条:乐观语义下图片从第一帧就以图的形态出现,不做「📎 附件行 → 正式消息
* 图片」的形态跳变。uri 缺失时按 ossRef 查 sentAttachmentThumbStore(订阅版本号,
* hydrate / 注册完成后自动补图);两者都拿不到时渲染 chip 底色占位格。
*/
@@ -129,7 +132,9 @@ function useThumbCellUri(
function ThumbCell({
thumb,
resolveRemoteMedia,
+ renderImage,
}: {
+ renderImage: (uri: string | null) => ReactNode;
thumb: MobileOutboxThumb;
resolveRemoteMedia?: ResolveRemoteMediaFn;
}) {
@@ -138,18 +143,7 @@ function ThumbCell({
const uri = useThumbCellUri(thumb, resolveRemoteMedia);
return (
<View style={styles.thumbCell}>
- {uri ? (
- <Image
- // 缓存命中优先:同一张图在气泡与回流后的正式消息之间复用解码结果,交接时不重绘。
- cachePolicy="memory-disk"
- contentFit="cover"
- // recyclingKey 绑到这一格:列表复用视图时不会短暂顶着上一条消息的图。
- recyclingKey={thumb.key}
- source={{ uri }}
- style={styles.thumbCellImage}
- transition={0}
- />
- ) : null}
+ {renderImage(uri)}
{thumb.uploading ? (
<View style={styles.thumbUploadingOverlay}>
<ActivityIndicator color={colors.ctaText} size="small" />
@@ -162,7 +156,11 @@ function ThumbCell({
function AttachmentThumbStrip({
thumbs,
resolveRemoteMedia,
+ renderImage,
+ gap,
}: {
+ renderImage: (uri: string | null) => ReactNode;
+ gap: number;
thumbs: readonly MobileOutboxThumb[];
resolveRemoteMedia?: ResolveRemoteMediaFn;
}) {
@@ -170,9 +168,9 @@ function AttachmentThumbStrip({
useSentAttachmentThumbsVersion();
if (thumbs.length === 0) return null;
return (
- <View style={styles.thumbStrip} testID="pendingSend.thumbStrip">
+ <View style={[styles.thumbStrip, { gap }]} testID="pendingSend.thumbStrip">
{thumbs.map((thumb) => (
- <ThumbCell key={thumb.key} resolveRemoteMedia={resolveRemoteMedia} thumb={thumb} />
+ <ThumbCell renderImage={renderImage} key={thumb.key} resolveRemoteMedia={resolveRemoteMedia} thumb={thumb} />
))}
</View>
);
@@ -182,7 +180,15 @@ export function PendingSendBubble({
item,
actions,
resolveRemoteMedia,
+ renderImage,
+ renderText,
+ renderFile,
+ screenWidth,
}: {
+ renderImage: (uri: string | null) => ReactNode;
+ renderText: (text: string, index: number) => ReactNode;
+ renderFile: (name: string, index: number) => ReactNode;
+ screenWidth?: number;
item: MobilePendingSendItem;
actions: PendingSendBubbleActions;
/** 远端媒体取件(粘贴时已上传到媒体总仓的图靠它取缩略图)。 */
@@ -198,23 +204,39 @@ export function PendingSendBubble({
const selected = isPendingSendItemSelected(item, actions.selectedClientId);
const bubbleLabel = item.text || t('message.queue.attachmentMessage');
const uploadsPending = item.phase === 'uploading';
+ const layout = buildMessageContentLayout({ screenWidth });
const rendersSentInlineBody = item.sentInlineTokens.some((token) => token.kind !== 'text');
+ const displayBody = rendersSentInlineBody ? sentInlineTokensDisplayText(item.sentInlineTokens) : item.text;
+ const density = summarizeMessageBubblePresentation({ kind: 'user', body: displayBody, attachmentCount: item.attachmentCount }).density;
+ const [measuredBody, setMeasuredBody] = useState<{ body: string; lines: number } | null>(null);
+ const [expandedBody, setExpandedBody] = useState<string | null>(null);
+ const measureBody = mayExceedVisualLineThreshold(displayBody);
+ const collapseResolved = measureBody && resolveUserMessageCollapse(
+ displayBody, measuredBody?.body === displayBody ? measuredBody.lines : null,
+ LONG_USER_MESSAGE_VISUAL_LINE_THRESHOLD,
+ );
+ const [collapseLatchBody, setCollapseLatchBody] = useState<string | null>(null);
+ const collapseLatched = collapseLatchBody === displayBody;
+ useEffect(() => {
+ if (collapseResolved && !collapseLatched) setCollapseLatchBody(displayBody);
+ }, [collapseResolved, collapseLatched, displayBody]);
+ const shouldCollapse = (measureBody && collapseLatched) || collapseResolved;
+ const expanded = expandedBody === displayBody;
+ const collapsedLines = shouldCollapse && !expanded ? LONG_USER_MESSAGE_COLLAPSED_LINES : undefined;
+ const hasBody = !!displayBody;
+ const hasAttachments = item.thumbs.length > 0 || !!item.fileNames?.length;
+ const [badgeAnchor, setBadgeAnchor] = useState<{ clientId: string; left: number } | null>(null);
+ const measureBadgeAnchor = (event: LayoutChangeEvent) => {
+ const left = Math.max(0, event.nativeEvent.layout.x - 28 - spacing.sm);
+ setBadgeAnchor((current) => current?.clientId === item.clientId && current.left === left
+ ? current : { clientId: item.clientId, left });
+ };
+ const badgePosition = badgeAnchor?.clientId === item.clientId
+ ? { left: badgeAnchor.left } : { right: 0 };
return (
<View style={styles.rowWrap} testID={`pendingSend.row.${item.clientId}`}>
<View style={styles.bubbleRow}>
- <View style={styles.badge} testID={`pendingSend.badge.${item.phase}`}>
- {failed ? (
- <AlertCircle color={colors.errorText} size={iconSize.sm} strokeWidth={iconStroke.regular} />
- ) : spinning ? (
- <ActivityIndicator color={colors.textTertiary} size="small" />
- ) : editing ? (
- <Pencil color={colors.textTertiary} size={iconSize.sm} strokeWidth={iconStroke.regular} />
- ) : (
- // 暂停态不换 ⏸:组顶横幅已表达暂停,逐条再换会重复;行内恒用排队 icon。
- <ListEnd color={colors.textTertiary} size={iconSize.sm} strokeWidth={iconStroke.regular} />
- )}
- </View>
<Pressable
accessibilityHint={item.hint ?? undefined}
accessibilityLabel={failed
@@ -227,33 +249,84 @@ export function PendingSendBubble({
accessibilityRole="button"
accessibilityState={{ expanded: selected, disabled: !interactive }}
disabled={!interactive}
- hitSlop={{ left: iconSize.xl + spacing.sm }}
+ hitSlop={spacing.sm}
onPress={() => actions.onSelect(selected ? null : item.clientId)}
- style={({ pressed }) => [
- styles.bubble,
+ style={({ pressed }) => [styles.badge, badgePosition, pressed && styles.pressed]}
+ testID={`pendingSend.badge.${item.phase}`}
+ >
+ {failed ? (
+ <AlertCircle color={colors.errorText} size={iconSize.sm} strokeWidth={iconStroke.regular} />
+ ) : spinning ? (
+ <ActivityIndicator color={colors.textTertiary} size="small" />
+ ) : editing ? (
+ <Pencil color={colors.textTertiary} size={iconSize.sm} strokeWidth={iconStroke.regular} />
+ ) : (
+ // 暂停态不换 ⏸:组顶横幅已表达暂停,逐条再换会重复;行内恒用排队 icon。
+ <ListEnd color={colors.textTertiary} size={iconSize.sm} strokeWidth={iconStroke.regular} />
+ )}
+ </Pressable>
+ <View
+ style={[
+ styles.content,
item.phase === 'settling' && styles.bubbleSettling,
selected && styles.bubbleSelected,
editing && styles.bubbleEditing,
- pressed && styles.pressed,
]}
testID={`pendingSend.bubble.${item.clientId}`}
>
- {rendersSentInlineBody ? (
- <SentInlineAtomBody
- interactiveAtoms={false}
- maxVisibleLines={selected ? undefined : 6}
- numberOfLines={selected ? undefined : 6}
- testID="pendingSend.sentInlineAtoms"
- textStyle={styles.bubbleText}
- tokens={item.sentInlineTokens}
- />
- ) : item.text ? (
- <Text numberOfLines={selected ? undefined : 6} style={styles.bubbleText}>
- {item.text}
- </Text>
+ {hasAttachments ? (
+ <View key={`attachments:${item.clientId}`} onLayout={measureBadgeAnchor} style={[styles.attachmentStrip, { gap: layout.attachmentGap }]}>
+ <AttachmentThumbStrip
+ gap={layout.attachmentGap}
+ renderImage={renderImage}
+ resolveRemoteMedia={resolveRemoteMedia}
+ thumbs={item.thumbs}
+ />
+ {item.fileNames?.length ? (
+ <View style={[styles.thumbStrip, { gap: layout.attachmentGap, maxWidth: layout.fileChipMaxWidth }]}>
+ {item.fileNames.map(renderFile)}
+ </View>
+ ) : null}
+ </View>
) : null}
- <AttachmentThumbStrip resolveRemoteMedia={resolveRemoteMedia} thumbs={item.thumbs} />
- {item.fileCount > 0 || uploadsPending ? (
+ {hasBody ? (
+ <View key={`body:${item.clientId}`} onLayout={hasAttachments ? undefined : measureBadgeAnchor} style={[styles.bubble, density === 'compact' && styles.bubbleCompact, density === 'rich' && styles.bubbleRich]}>
+ {rendersSentInlineBody ? (
+ <SentInlineAtomBody
+ interactiveAtoms={false}
+ maxVisibleLines={collapsedLines}
+ numberOfLines={collapsedLines}
+ renderText={collapsedLines ? undefined : (text, index) => (
+ <View key={`text:${index}`} style={styles.textChunk}>{renderText(text, index)}</View>
+ )}
+ testID="pendingSend.sentInlineAtoms"
+ textStyle={styles.bubbleText}
+ tokens={item.sentInlineTokens}
+ />
+ ) : item.text && !collapsedLines ? renderText(item.text, 0) : item.text ? (
+ <Text numberOfLines={collapsedLines} style={styles.bubbleText}>
+ {item.text}
+ </Text>
+ ) : null}
+ {measureBody ? (
+ <View accessibilityElementsHidden accessible={false} importantForAccessibility="no-hide-descendants"
+ pointerEvents="none" style={styles.collapseMeasureWrap}>
+ <Text numberOfLines={LONG_USER_MESSAGE_VISUAL_LINE_THRESHOLD + 1}
+ onTextLayout={(event) => setMeasuredBody({ body: displayBody, lines: event.nativeEvent.lines.length })}
+ style={styles.bubbleText}>{displayBody}</Text>
+ </View>
+ ) : null}
+ {shouldCollapse ? (
+ <Text accessibilityRole="button" suppressHighlighting
+ accessibilityLabel={expanded ? t('message.renderer.collapseMessage') : t('message.renderer.expandMessage')}
+ onPress={(event) => { event.stopPropagation(); setExpandedBody(expanded ? null : displayBody); }}
+ style={styles.collapseToggleText}>
+ {expanded ? t('message.renderer.collapse') : t('message.renderer.expand')}
+ </Text>
+ ) : null}
+ </View>
+ ) : null}
+ {(item.fileCount > 0 && !item.fileNames?.length) || uploadsPending ? (
<View style={styles.attachmentLine}>
<Paperclip color={colors.textTertiary} size={iconSize.xs} strokeWidth={iconStroke.regular} />
<Text style={styles.attachmentLineText}>
@@ -276,7 +349,7 @@ export function PendingSendBubble({
{item.errorText}
</Text>
) : null}
- </Pressable>
+ </View>
</View>
{selected && item.hint ? (
<Text style={styles.rowHint} testID={`pendingSend.hint.${item.clientId}`}>{item.hint}</Text>
@@ -389,8 +462,12 @@ const makeStyles = (colors: ThemeColors) => StyleSheet.create({
justifyContent: 'flex-end',
width: '100%',
},
- badge: { alignItems: 'center', flexDirection: 'row' },
+ badge: { alignItems: 'center', justifyContent: 'center', width: 28, minHeight: 44, position: 'absolute', top: 0, zIndex: 1 },
// 与已发送用户气泡同款,但整体半透明:「这就是你的消息,只是还没生效」。
+ textChunk: { flexBasis: '100%', flexShrink: 1, maxWidth: '100%' },
+ content: { alignItems: 'flex-end', gap: 2, width: '100%', opacity: 0.62 },
+ bubbleCompact: { gap: 6, paddingVertical: spacing.sm },
+ bubbleRich: { gap: spacing.sm },
bubble: {
backgroundColor: colors.surfaceElevated,
borderColor: colors.borderStrong,
@@ -398,10 +475,13 @@ const makeStyles = (colors: ThemeColors) => StyleSheet.create({
borderWidth: StyleSheet.hairlineWidth,
gap: spacing.xs,
maxWidth: '86%',
- opacity: 0.62,
+ minWidth: 0,
+ overflow: 'hidden',
padding: spacing.md,
},
- bubbleSelected: { borderColor: colors.textSecondary, opacity: 1 },
+ collapseMeasureWrap: { left: spacing.md, right: spacing.md, top: 0, opacity: 0, position: 'absolute' },
+ collapseToggleText: { alignSelf: 'flex-start', color: colors.textSecondary, fontSize: typeScale.caption, lineHeight: lineHeight.caption, paddingVertical: spacing.xs },
+ bubbleSelected: { opacity: 1 },
bubbleEditing: { opacity: 0.38 },
// 落定中:即将变实,透明度介于排队(0.62)与已发送(1)之间。
bubbleSettling: { opacity: 0.85 },
@@ -412,17 +492,9 @@ const makeStyles = (colors: ThemeColors) => StyleSheet.create({
},
attachmentLine: { alignItems: 'center', flexDirection: 'row', gap: 4 },
attachmentLineText: { color: colors.textTertiary, fontSize: typeScale.footnote },
- thumbStrip: { flexDirection: 'row', flexWrap: 'wrap', gap: spacing.xs, justifyContent: 'flex-end' },
- thumbCell: {
- backgroundColor: colors.surfaceChip,
- borderColor: colors.border,
- borderRadius: radius.container,
- borderWidth: StyleSheet.hairlineWidth,
- height: 72,
- overflow: 'hidden',
- width: 72,
- },
- thumbCellImage: { height: '100%', width: '100%' },
+ attachmentStrip: { alignItems: 'flex-end', marginBottom: spacing.xs, maxWidth: '100%' },
+ thumbStrip: { alignItems: 'flex-end', maxWidth: '100%' },
+ thumbCell: { borderRadius: radius.container, overflow: 'hidden' },
thumbUploadingOverlay: {
alignItems: 'center',
backgroundColor: colors.overlay,
diff --git a/apps/mobile/src/session/mobileLocalAttachmentUpload.ts b/apps/mobile/src/session/mobileLocalAttachmentUpload.ts
index a18e3f7074..76f60747ee 100644
--- a/apps/mobile/src/session/mobileLocalAttachmentUpload.ts
+++ b/apps/mobile/src/session/mobileLocalAttachmentUpload.ts
@@ -181,7 +181,7 @@ export interface MobileLocalAttachmentUploadController {
* 要带走哪些在途上传」。failed = 已失败结算的卡(claim 后随消息进失败态);
* kind / previewUri 供乐观消息气泡直接渲染本地缩略图(图片 = candidate.uri)。
*/
- claimableTasks(): Array<{ localId: string; failed: boolean; kind: MobileLocalAttachmentKind; previewUri: string }>;
+ claimableTasks(): Array<{ localId: string; failed: boolean; kind: MobileLocalAttachmentKind; previewUri: string; name: string }>;
/** 退屏兜底:全部标记丢弃(不再回调 onUploaded/onFailed,完成后回收 OSS)。 */
dispose(): void;
}
@@ -558,6 +558,7 @@ export function createMobileLocalAttachmentUploadController(
failed: boolean;
kind: MobileLocalAttachmentKind;
previewUri: string;
+ name: string;
}> = [];
for (const task of tasks.values()) {
if (task.discarded || task.claimed) continue;
@@ -566,6 +567,7 @@ export function createMobileLocalAttachmentUploadController(
failed: task.state === 'failed',
kind: task.candidate.kind,
previewUri: task.candidate.uri,
+ name: task.candidate.name,
});
}
return out;
diff --git a/apps/mobile/src/session/pendingSendItems.ts b/apps/mobile/src/session/pendingSendItems.ts
index cd04467a2a..4ee48aa836 100644
--- a/apps/mobile/src/session/pendingSendItems.ts
+++ b/apps/mobile/src/session/pendingSendItems.ts
@@ -63,6 +63,7 @@ export interface MobilePendingSendItem {
thumbs: MobileOutboxThumb[];
/** 非图片附件数(pdf / office 等,渲染「N 个文件」计数行)。 */
fileCount: number;
+ fileNames?: string[];
/** 附件总数与已上传数(uploading 阶段渲染「上传中 k/N」)。 */
attachmentCount: number;
uploadedCount: number;
@@ -231,6 +232,7 @@ export function buildPendingSendItems(input: BuildPendingSendItemsInput): Mobile
queueIndex,
thumbs: attachments.thumbs,
fileCount: attachments.fileCount,
+ fileNames: (item.files ?? []).filter((file) => file.category !== 'image').map((file) => file.name),
attachmentCount: attachments.thumbs.length + attachments.fileCount,
uploadedCount: attachments.thumbs.length + attachments.fileCount,
errorText: null,
@@ -268,6 +270,7 @@ export function buildPendingSendItems(input: BuildPendingSendItemsInput): Mobile
queueIndex: null,
thumbs: item.thumbnails,
fileCount: item.fileCount,
+ fileNames: item.fileNames,
attachmentCount: item.attachmentCount,
uploadedCount: item.uploadedCount,
errorText: item.errorText,
diff --git a/apps/mobile/src/session/sessionOutbox.ts b/apps/mobile/src/session/sessionOutbox.ts
index 696407c8a7..4d74558f19 100644
--- a/apps/mobile/src/session/sessionOutbox.ts
+++ b/apps/mobile/src/session/sessionOutbox.ts
@@ -133,7 +133,7 @@ export interface MobileOutboxItem {
* (图片 = 缩略图方块,文件 = 计数行),previewUri 为本地预览(file://,
* 上传中即可显示——乐观语义下图从第一帧就该以图的形态出现,不做「附件→图片」跳变)。
*/
- slotMeta: ReadonlyArray<{ kind: 'image' | 'file'; previewUri: string | null }>;
+ slotMeta: ReadonlyArray<{ kind: 'image' | 'file'; previewUri: string | null; name?: string }>;
/** 上传任务 localId → 槽位下标。 */
slotByLocalId: Readonly<Record<string, number>>;
/** 尚未落定的上传任务。 */
@@ -169,6 +169,7 @@ export interface MobileOutboxDisplayItem {
thumbnails: MobileOutboxThumb[];
/** 非图片附件数(pdf / office 等,渲染「N 个文件」计数行)。 */
fileCount: number;
+ fileNames?: string[];
failed: boolean;
/** 失败原因(附件失败给统一文案,enqueue 失败给 RPC 错误)。 */
errorText: string | null;
@@ -213,12 +214,14 @@ export function buildOutboxItem(input: {
failed: boolean;
kind?: 'image' | 'file';
previewUri?: string;
+ name?: string;
}>;
}): MobileOutboxItem {
const slots: Array<RemoteSerializedAttachment | null> = [...input.readyAttachments];
- const slotMeta: Array<{ kind: 'image' | 'file'; previewUri: string | null }> =
+ const slotMeta: Array<{ kind: 'image' | 'file'; previewUri: string | null; name?: string }> =
input.readyAttachments.map((attachment, index) => ({
kind: attachment.category === 'image' ? 'image' : 'file',
+ name: attachment.name,
previewUri: input.readyPreviews?.[index] ?? null,
}));
const slotByLocalId: Record<string, number> = {};
@@ -227,7 +230,7 @@ export function buildOutboxItem(input: {
for (const upload of input.claimedUploads) {
slotByLocalId[upload.localId] = slots.length;
slots.push(null);
- slotMeta.push({ kind: upload.kind ?? 'image', previewUri: upload.previewUri ?? null });
+ slotMeta.push({ kind: upload.kind ?? 'image', previewUri: upload.previewUri ?? null, name: upload.name });
if (upload.failed) failedIds.push(upload.localId);
else waitingIds.push(upload.localId);
}
@@ -416,10 +419,12 @@ export function outboxDisplayItem(item: MobileOutboxItem): MobileOutboxDisplayIt
const uploadedCount = item.attachmentSlots.filter((slot) => slot !== null).length;
const thumbnails: MobileOutboxThumb[] = [];
let fileCount = 0;
+ const fileNames: string[] = [];
item.attachmentSlots.forEach((slot, index) => {
const meta = item.slotMeta[index];
if (meta?.kind !== 'image') {
fileCount += 1;
+ fileNames.push(slot?.name ?? meta?.name ?? i18n.t('message.queue.attachmentMessage'));
return;
}
thumbnails.push({
@@ -439,6 +444,7 @@ export function outboxDisplayItem(item: MobileOutboxItem): MobileOutboxDisplayIt
uploadedCount,
thumbnails,
fileCount,
+ fileNames,
failed: item.phase === 'failed',
errorText: item.phase !== 'failed'
? null