Skip to content

armgit / ente

Public Imported from GitHub
0

πŸ’š End-to-end encrypted cloud for everything.

Improve image thumbnails designs and view

laurenspriem0a5ad3c7f2d6
diff --git a/mobile/native/android/apps/ensu/app-ui/src/main/java/io/ente/ensu/HomeView.kt b/mobile/native/android/apps/ensu/app-ui/src/main/java/io/ente/ensu/HomeView.kt
index 2c95d47c5d..372a1efa80 100644
--- a/mobile/native/android/apps/ensu/app-ui/src/main/java/io/ente/ensu/HomeView.kt
+++ b/mobile/native/android/apps/ensu/app-ui/src/main/java/io/ente/ensu/HomeView.kt
@@ -52,6 +52,7 @@ import androidx.navigation.compose.currentBackStackEntryAsState
import com.google.accompanist.navigation.animation.rememberAnimatedNavController
import io.ente.ensu.auth.AuthFlowScreen
import io.ente.ensu.chat.SessionDrawer
+import io.ente.ensu.components.ImageAttachmentPreviewDialog
import io.ente.ensu.components.NativeChoiceDialog
import io.ente.ensu.data.AdvancedSettingsDataStore
import io.ente.ensu.data.auth.EnsuAuthService
@@ -103,6 +104,7 @@ fun HomeView(
var deleteSessionTarget by remember { mutableStateOf<io.ente.ensu.domain.model.ChatSession?>(null) }
var showLogShareDialog by remember { mutableStateOf(false) }
var showSignInComingSoon by remember { mutableStateOf(false) }
+ var imagePreviewAttachment by remember { mutableStateOf<Attachment?>(null) }
val handleSignInRequest: () -> Unit = handle@{
if (!EnsuFeatureFlags.enableSignIn) {
@@ -280,11 +282,25 @@ fun HomeView(
onAttachmentDownloads = { showAttachmentDownloads = true },
onShowLogShareDialog = { showLogShareDialog = true },
onAttachmentSelected = handleAttachmentSelected,
- onOpenAttachment = { attachment -> openAttachment(context, attachment) },
+ onOpenAttachment = { attachment ->
+ if (attachment.type == AttachmentType.Image) {
+ imagePreviewAttachment = attachment
+ } else {
+ openAttachment(context, attachment)
+ }
+ },
onDeleteAccount = { openDeleteAccountEmail(context) }
)
}
+ imagePreviewAttachment?.let { attachment ->
+ ImageAttachmentPreviewDialog(
+ path = attachment.localPath,
+ contentDescription = attachment.name,
+ onDismiss = { imagePreviewAttachment = null }
+ )
+ }
+
AnimatedVisibility(
visible = isShowingAuth,
enter = slideInHorizontally(
diff --git a/mobile/native/android/apps/ensu/app-ui/src/main/java/io/ente/ensu/chat/ChatMessages.kt b/mobile/native/android/apps/ensu/app-ui/src/main/java/io/ente/ensu/chat/ChatMessages.kt
index ff56d93586..53bedf395d 100644
--- a/mobile/native/android/apps/ensu/app-ui/src/main/java/io/ente/ensu/chat/ChatMessages.kt
+++ b/mobile/native/android/apps/ensu/app-ui/src/main/java/io/ente/ensu/chat/ChatMessages.kt
@@ -515,6 +515,9 @@ private fun UserMessageBubble(
contentDescription = attachment.name,
width = 164.dp,
height = 124.dp,
+ portraitWidth = 124.dp,
+ portraitHeight = 164.dp,
+ squareSize = 140.dp,
isUploading = attachment.isUploading,
onClick = { onOpenAttachment(attachment) }
)
diff --git a/mobile/native/android/apps/ensu/app-ui/src/main/java/io/ente/ensu/components/ImageAttachmentThumbnail.kt b/mobile/native/android/apps/ensu/app-ui/src/main/java/io/ente/ensu/components/ImageAttachmentThumbnail.kt
index d29b0e9253..9144ae0947 100644
--- a/mobile/native/android/apps/ensu/app-ui/src/main/java/io/ente/ensu/components/ImageAttachmentThumbnail.kt
+++ b/mobile/native/android/apps/ensu/app-ui/src/main/java/io/ente/ensu/components/ImageAttachmentThumbnail.kt
@@ -3,9 +3,9 @@ package io.ente.ensu.components
import android.graphics.BitmapFactory
import androidx.compose.foundation.Image
import androidx.compose.foundation.background
-import androidx.compose.foundation.border
import androidx.compose.foundation.clickable
import androidx.compose.foundation.layout.Box
+import androidx.compose.foundation.layout.BoxWithConstraints
import androidx.compose.foundation.layout.fillMaxSize
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.layout.size
@@ -29,9 +29,12 @@ import androidx.compose.ui.platform.LocalDensity
import androidx.compose.ui.res.painterResource
import androidx.compose.ui.unit.Dp
import androidx.compose.ui.unit.dp
+import androidx.compose.ui.window.Dialog
+import androidx.compose.ui.window.DialogProperties
import io.ente.ensu.designsystem.EnsuColor
import io.ente.ensu.designsystem.EnsuCornerRadius
import io.ente.ensu.designsystem.HugeIcons
+import io.ente.ensu.designsystem.EnsuSpacing
import io.ente.ensu.utils.rememberEnsuHaptics
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.withContext
@@ -43,18 +46,33 @@ fun ImageAttachmentThumbnail(
width: Dp,
height: Dp,
modifier: Modifier = Modifier,
+ portraitWidth: Dp? = null,
+ portraitHeight: Dp? = null,
+ squareSize: Dp? = null,
isUploading: Boolean = false,
onDelete: (() -> Unit)? = null,
onClick: (() -> Unit)? = null
) {
val density = LocalDensity.current
- val targetWidthPx = with(density) { width.roundToPx() }
- val targetHeightPx = with(density) { height.roundToPx() }
- val bitmap by produceState<ImageBitmap?>(initialValue = null, path, targetWidthPx, targetHeightPx) {
+ val maxWidth = maxOf(width, portraitWidth ?: width, squareSize ?: width)
+ val maxHeight = maxOf(height, portraitHeight ?: height, squareSize ?: height)
+ val targetWidthPx = with(density) { maxWidth.roundToPx() }
+ val targetHeightPx = with(density) { maxHeight.roundToPx() }
+ val image by produceState<DecodedImage?>(initialValue = null, path, targetWidthPx, targetHeightPx) {
value = decodeSampledImage(path, targetWidthPx, targetHeightPx)
}
val haptic = rememberEnsuHaptics()
val shape = RoundedCornerShape(EnsuCornerRadius.card.dp)
+ val resolvedWidth = when {
+ image?.isPortrait == true && portraitWidth != null -> portraitWidth
+ image?.isSquare == true && squareSize != null -> squareSize
+ else -> width
+ }
+ val resolvedHeight = when {
+ image?.isPortrait == true && portraitHeight != null -> portraitHeight
+ image?.isSquare == true && squareSize != null -> squareSize
+ else -> height
+ }
val clickModifier = if (onClick != null) {
Modifier.clickable {
haptic.perform(HapticFeedbackType.TextHandleMove)
@@ -66,16 +84,15 @@ fun ImageAttachmentThumbnail(
Box(
modifier = modifier
- .size(width = width, height = height)
+ .size(width = resolvedWidth, height = resolvedHeight)
.clip(shape)
.background(EnsuColor.fillFaint(), shape)
- .border(1.dp, EnsuColor.border().copy(alpha = 0.7f), shape)
.then(clickModifier),
contentAlignment = Alignment.Center
) {
- if (bitmap != null) {
+ if (image != null) {
Image(
- bitmap = bitmap!!,
+ bitmap = image!!.bitmap,
contentDescription = contentDescription,
modifier = Modifier.fillMaxSize(),
contentScale = ContentScale.Crop
@@ -105,21 +122,83 @@ fun ImageAttachmentThumbnail(
}
if (onDelete != null) {
- IconButton(
- onClick = {
- haptic.perform(HapticFeedbackType.LongPress)
- onDelete()
- },
+ Box(
modifier = Modifier
.align(Alignment.TopEnd)
.padding(4.dp)
- .size(28.dp)
+ .size(20.dp)
.background(Color.Black.copy(alpha = 0.42f), CircleShape)
+ .clickable {
+ haptic.perform(HapticFeedbackType.LongPress)
+ onDelete()
+ },
+ contentAlignment = Alignment.Center
) {
Icon(
painter = painterResource(HugeIcons.Cancel01Icon),
contentDescription = "Remove image",
- modifier = Modifier.size(12.dp),
+ modifier = Modifier.size(9.dp),
+ tint = Color.White
+ )
+ }
+ }
+ }
+}
+
+@Composable
+fun ImageAttachmentPreviewDialog(
+ path: String?,
+ contentDescription: String?,
+ onDismiss: () -> Unit
+) {
+ val density = LocalDensity.current
+ Dialog(
+ onDismissRequest = onDismiss,
+ properties = DialogProperties(usePlatformDefaultWidth = false)
+ ) {
+ BoxWithConstraints(
+ modifier = Modifier
+ .fillMaxSize()
+ .background(Color.Black.copy(alpha = 0.94f))
+ ) {
+ val targetWidthPx = with(density) { maxWidth.roundToPx() }
+ val targetHeightPx = with(density) { maxHeight.roundToPx() }
+ val image by produceState<DecodedImage?>(initialValue = null, path, targetWidthPx, targetHeightPx) {
+ value = decodeSampledImage(path, targetWidthPx, targetHeightPx)
+ }
+
+ if (image != null) {
+ Image(
+ bitmap = image!!.bitmap,
+ contentDescription = contentDescription,
+ modifier = Modifier
+ .fillMaxSize()
+ .padding(EnsuSpacing.md.dp),
+ contentScale = ContentScale.Fit
+ )
+ } else {
+ Icon(
+ painter = painterResource(HugeIcons.Attachment01Icon),
+ contentDescription = contentDescription,
+ modifier = Modifier
+ .align(Alignment.Center)
+ .size(32.dp),
+ tint = Color.White.copy(alpha = 0.7f)
+ )
+ }
+
+ IconButton(
+ onClick = onDismiss,
+ modifier = Modifier
+ .align(Alignment.TopEnd)
+ .padding(EnsuSpacing.lg.dp)
+ .size(32.dp)
+ .background(Color.Black.copy(alpha = 0.35f), CircleShape)
+ ) {
+ Icon(
+ painter = painterResource(HugeIcons.Cancel01Icon),
+ contentDescription = "Close image preview",
+ modifier = Modifier.size(14.dp),
tint = Color.White
)
}
@@ -127,11 +206,18 @@ fun ImageAttachmentThumbnail(
}
}
+private data class DecodedImage(
+ val bitmap: ImageBitmap
+) {
+ val isPortrait: Boolean = bitmap.height > bitmap.width
+ val isSquare: Boolean = bitmap.height == bitmap.width
+}
+
private suspend fun decodeSampledImage(
path: String?,
targetWidthPx: Int,
targetHeightPx: Int
-): ImageBitmap? = withContext(Dispatchers.IO) {
+): DecodedImage? = withContext(Dispatchers.IO) {
if (path.isNullOrBlank() || targetWidthPx <= 0 || targetHeightPx <= 0) {
return@withContext null
}
@@ -153,7 +239,7 @@ private suspend fun decodeSampledImage(
)
}
- BitmapFactory.decodeFile(path, options)?.asImageBitmap()
+ BitmapFactory.decodeFile(path, options)?.asImageBitmap()?.let(::DecodedImage)
}
private fun calculateInSampleSize(
diff --git a/mobile/native/darwin/Apps/Ensu/Ensu/Chat/MessageList/MessageListComponents.swift b/mobile/native/darwin/Apps/Ensu/Ensu/Chat/MessageList/MessageListComponents.swift
index 399fbda2d2..c786d8ca75 100644
--- a/mobile/native/darwin/Apps/Ensu/Ensu/Chat/MessageList/MessageListComponents.swift
+++ b/mobile/native/darwin/Apps/Ensu/Ensu/Chat/MessageList/MessageListComponents.swift
@@ -109,6 +109,9 @@ struct UserMessageBubbleView: View {
accessibilityLabel: attachment.name,
width: 164,
height: 124,
+ portraitWidth: 124,
+ portraitHeight: 164,
+ squareSize: 140,
isUploading: attachment.isUploading
)
.onTapGesture {
diff --git a/mobile/native/darwin/Apps/Ensu/Ensu/Components/EnsuComponents.swift b/mobile/native/darwin/Apps/Ensu/Ensu/Components/EnsuComponents.swift
index ff9fa91c35..8308e91e7f 100644
--- a/mobile/native/darwin/Apps/Ensu/Ensu/Components/EnsuComponents.swift
+++ b/mobile/native/darwin/Apps/Ensu/Ensu/Components/EnsuComponents.swift
@@ -186,29 +186,31 @@ struct ImageAttachmentThumbnail: View {
let accessibilityLabel: String
var width: CGFloat
var height: CGFloat
+ var portraitWidth: CGFloat? = nil
+ var portraitHeight: CGFloat? = nil
+ var squareSize: CGFloat? = nil
var isUploading: Bool = false
var onDelete: (() -> Void)? = nil
var body: some View {
+ let loadedImage = platformImage(from: url)
+ let size = thumbnailSize(for: loadedImage)
+
ZStack(alignment: .topTrailing) {
- thumbnailContent
- .frame(width: width, height: height)
+ thumbnailContent(loadedImage)
+ .frame(width: size.width, height: size.height)
.background(EnsuColor.fillFaint)
.clipShape(RoundedRectangle(cornerRadius: EnsuCornerRadius.card, style: .continuous))
- .overlay {
- RoundedRectangle(cornerRadius: EnsuCornerRadius.card, style: .continuous)
- .stroke(EnsuColor.border.opacity(0.7), lineWidth: 0.5)
- }
.contentShape(RoundedRectangle(cornerRadius: EnsuCornerRadius.card, style: .continuous))
if isUploading {
RoundedRectangle(cornerRadius: EnsuCornerRadius.card, style: .continuous)
.fill(.black.opacity(0.18))
- .frame(width: width, height: height)
+ .frame(width: size.width, height: size.height)
ProgressView()
.scaleEffect(0.8)
- .frame(width: width, height: height)
+ .frame(width: size.width, height: size.height)
}
if let onDelete {
@@ -223,7 +225,7 @@ struct ImageAttachmentThumbnail: View {
.foregroundStyle(.white)
}
.buttonStyle(.plain)
- .frame(width: 28, height: 28)
+ .frame(width: 20, height: 20)
.background(.black.opacity(0.45))
.clipShape(Circle())
.padding(4)
@@ -234,9 +236,9 @@ struct ImageAttachmentThumbnail: View {
}
@ViewBuilder
- private var thumbnailContent: some View {
- if let image = platformImage(from: url) {
- image
+ private func thumbnailContent(_ loadedImage: PlatformImageContent?) -> some View {
+ if let loadedImage {
+ loadedImage.image
.resizable()
.scaledToFill()
} else {
@@ -248,7 +250,23 @@ struct ImageAttachmentThumbnail: View {
}
}
- private func platformImage(from url: URL?) -> Image? {
+ private func thumbnailSize(for loadedImage: PlatformImageContent?) -> CGSize {
+ guard let loadedImage else {
+ return CGSize(width: width, height: height)
+ }
+ if loadedImage.pixelHeight > loadedImage.pixelWidth,
+ let portraitWidth,
+ let portraitHeight {
+ return CGSize(width: portraitWidth, height: portraitHeight)
+ }
+ if loadedImage.pixelHeight == loadedImage.pixelWidth,
+ let squareSize {
+ return CGSize(width: squareSize, height: squareSize)
+ }
+ return CGSize(width: width, height: height)
+ }
+
+ private func platformImage(from url: URL?) -> PlatformImageContent? {
guard let url else {
return nil
}
@@ -257,18 +275,32 @@ struct ImageAttachmentThumbnail: View {
guard let image = UIImage(contentsOfFile: url.path) else {
return nil
}
- return Image(uiImage: image)
+ return PlatformImageContent(
+ image: Image(uiImage: image),
+ pixelWidth: image.size.width,
+ pixelHeight: image.size.height
+ )
#elseif os(macOS)
guard let image = NSImage(contentsOf: url) else {
return nil
}
- return Image(nsImage: image)
+ return PlatformImageContent(
+ image: Image(nsImage: image),
+ pixelWidth: image.size.width,
+ pixelHeight: image.size.height
+ )
#else
return nil
#endif
}
}
+private struct PlatformImageContent {
+ let image: Image
+ let pixelWidth: CGFloat
+ let pixelHeight: CGFloat
+}
+
struct ToastView: View {
let message: String
@@ -444,6 +476,9 @@ struct ImageAttachmentThumbnail: View {
let accessibilityLabel: String
var width: CGFloat
var height: CGFloat
+ var portraitWidth: CGFloat? = nil
+ var portraitHeight: CGFloat? = nil
+ var squareSize: CGFloat? = nil
var isUploading: Bool = false
var onDelete: (() -> Void)? = nil
diff --git a/web/apps/ensu/src/components/chat/ChatComposer.tsx b/web/apps/ensu/src/components/chat/ChatComposer.tsx
index 2ab6803240..4cebc877b5 100644
--- a/web/apps/ensu/src/components/chat/ChatComposer.tsx
+++ b/web/apps/ensu/src/components/chat/ChatComposer.tsx
@@ -431,8 +431,6 @@ export const ChatComposer = memo(
height: 76,
borderRadius: 2,
bgcolor: "fill.faint",
- border: "1px solid",
- borderColor: "divider",
overflow: "hidden",
display: "flex",
alignItems: "center",
@@ -473,8 +471,8 @@ export const ChatComposer = memo(
"absolute",
top: 4,
right: 4,
- width: 24,
- height: 24,
+ width: 20,
+ height: 20,
p: 0,
borderRadius:
"999px",
@@ -496,7 +494,10 @@ export const ChatComposer = memo(
>
<HugeiconsIcon
icon={Cancel01Icon}
- {...smallIconProps}
+ size={11}
+ strokeWidth={
+ smallIconProps.strokeWidth
+ }
/>
</IconButton>
</Box>
diff --git a/web/apps/ensu/src/components/chat/ChatDialogs.tsx b/web/apps/ensu/src/components/chat/ChatDialogs.tsx
index 0a6dcbbde7..8f2a034733 100644
--- a/web/apps/ensu/src/components/chat/ChatDialogs.tsx
+++ b/web/apps/ensu/src/components/chat/ChatDialogs.tsx
@@ -113,6 +113,8 @@ export interface ChatDialogsProps {
setSyncNotificationOpen: React.Dispatch<React.SetStateAction<boolean>>;
syncNotification?: NotificationAttributes;
modelGateStatus: ModelGateStatus;
+ imagePreview: { url: string; name: string } | null;
+ closeImagePreview: () => void;
}
export const ChatDialogs = memo(
@@ -168,6 +170,8 @@ export const ChatDialogs = memo(
setSyncNotificationOpen,
syncNotification,
modelGateStatus,
+ imagePreview,
+ closeImagePreview,
}: ChatDialogsProps) => {
const openExternalUrl = async (url: string) => {
const hasTauriBridge =
@@ -367,6 +371,74 @@ export const ChatDialogs = memo(
return (
<>
+ <Dialog
+ open={!!imagePreview}
+ onClose={closeImagePreview}
+ maxWidth={false}
+ fullScreen={isSmall}
+ aria-label={imagePreview?.name || "Image preview"}
+ slotProps={{
+ paper: {
+ sx: {
+ m: 0,
+ width: "100vw",
+ height: "100svh",
+ maxWidth: "none",
+ maxHeight: "none",
+ borderRadius: 0,
+ bgcolor: "rgba(0, 0, 0, 0.94)",
+ boxShadow: "none",
+ overflow: "hidden",
+ },
+ },
+ }}
+ >
+ <DialogContent
+ sx={{
+ position: "relative",
+ p: { xs: 2, sm: 3 },
+ display: "flex",
+ alignItems: "center",
+ justifyContent: "center",
+ overflow: "hidden",
+ }}
+ >
+ {imagePreview && (
+ <Box
+ component="img"
+ src={imagePreview.url}
+ alt={imagePreview.name}
+ sx={{
+ display: "block",
+ maxWidth: "100%",
+ maxHeight: "100%",
+ objectFit: "contain",
+ borderRadius: 1,
+ }}
+ />
+ )}
+ <IconButton
+ aria-label="Close image preview"
+ onClick={closeImagePreview}
+ sx={{
+ position: "absolute",
+ top: { xs: 12, sm: 16 },
+ right: { xs: 12, sm: 16 },
+ width: 36,
+ height: 36,
+ color: "common.white",
+ bgcolor: "rgba(0, 0, 0, 0.38)",
+ "&:hover": { bgcolor: "rgba(0, 0, 0, 0.54)" },
+ }}
+ >
+ <HugeiconsIcon
+ icon={Cancel01Icon}
+ {...smallIconProps}
+ />
+ </IconButton>
+ </DialogContent>
+ </Dialog>
+
<Dialog
open={showSettingsModal}
onClose={closeSettingsModal}
diff --git a/web/apps/ensu/src/components/chat/ChatMessageList.tsx b/web/apps/ensu/src/components/chat/ChatMessageList.tsx
index 17b19f8791..a97710c7e3 100644
--- a/web/apps/ensu/src/components/chat/ChatMessageList.tsx
+++ b/web/apps/ensu/src/components/chat/ChatMessageList.tsx
@@ -11,7 +11,7 @@ import { Box, IconButton, Stack, Typography } from "@mui/material";
import type { SxProps, Theme } from "@mui/material/styles";
import { MarkdownRenderer } from "components/MarkdownRenderer";
import GeneratingRiveIndicator from "components/chat/GeneratingRiveIndicator";
-import React, { memo, useCallback, useEffect, useMemo } from "react";
+import React, { memo, useCallback, useEffect, useMemo, useState } from "react";
import {
STREAMING_SELECTION_KEY,
type BranchSwitcher,
@@ -74,6 +74,22 @@ interface ImageAttachmentThumbnailProps {
const ImageAttachmentThumbnail = memo(
({ attachment, previewUrl, onClick }: ImageAttachmentThumbnailProps) => {
+ const [orientation, setOrientation] = useState<
+ "landscape" | "portrait" | "square"
+ >("landscape");
+ const size =
+ orientation === "portrait"
+ ? { width: { xs: 112, sm: 124 }, height: { xs: 148, sm: 164 } }
+ : orientation === "square"
+ ? {
+ width: { xs: 132, sm: 140 },
+ height: { xs: 132, sm: 140 },
+ }
+ : {
+ width: { xs: 148, sm: 164 },
+ height: { xs: 112, sm: 124 },
+ };
+
return (
<Box
component="button"
@@ -81,11 +97,10 @@ const ImageAttachmentThumbnail = memo(
aria-label={attachment.name || "Open image attachment"}
onClick={onClick}
sx={{
- width: { xs: 148, sm: 164 },
- height: { xs: 112, sm: 124 },
+ width: size.width,
+ height: size.height,
p: 0,
- border: "1px solid",
- borderColor: "divider",
+ border: 0,
borderRadius: 2,
bgcolor: "fill.faint",
cursor: "pointer",
@@ -103,6 +118,16 @@ const ImageAttachmentThumbnail = memo(
component="img"
src={previewUrl}
alt={attachment.name || "Image attachment"}
+ onLoad={(event) => {
+ const img = event.currentTarget;
+ if (img.naturalHeight > img.naturalWidth) {
+ setOrientation("portrait");
+ } else if (img.naturalHeight === img.naturalWidth) {
+ setOrientation("square");
+ } else {
+ setOrientation("landscape");
+ }
+ }}
sx={{
width: "100%",
height: "100%",
diff --git a/web/apps/ensu/src/pages/chat.tsx b/web/apps/ensu/src/pages/chat.tsx
index 6c20f425dd..1d4ebc5a3a 100644
--- a/web/apps/ensu/src/pages/chat.tsx
+++ b/web/apps/ensu/src/pages/chat.tsx
@@ -589,6 +589,10 @@ const Page: React.FC = () => {
const [pendingImagePreviews, setPendingImagePreviews] = useState<
Record<string, string>
>({});
+ const [imagePreview, setImagePreview] = useState<{
+ url: string;
+ name: string;
+ } | null>(null);
const [downloadStatus, setDownloadStatus] =
useState<DownloadProgress | null>(null);
const [loadedModelName, setLoadedModelName] = useState<string | null>(null);
@@ -619,6 +623,7 @@ const Page: React.FC = () => {
const inputRef = useRef<HTMLTextAreaElement | null>(null);
const attachmentPreviewUrlsRef = useRef<Record<string, string>>({});
const pendingPreviewUrlsRef = useRef<Record<string, string>>({});
+ const imagePreviewUrlRef = useRef<string | null>(null);
const attachmentPreviewInFlightRef = useRef<Record<string, Promise<void>>>(
{},
);
@@ -1954,7 +1959,9 @@ const Page: React.FC = () => {
const paths = await Promise.all(
images.map(async (image) => {
- const bytes = new Uint8Array(await image.file.arrayBuffer());
+ const bytes = new Uint8Array(
+ await image.file.arrayBuffer(),
+ );
const path = await join(dir, `${image.id}.jpg`);
await writeBinaryFile({ path, contents: bytes });
return path;
@@ -2566,6 +2573,14 @@ const Page: React.FC = () => {
[showToast],
);
+ const closeImagePreview = useCallback(() => {
+ setImagePreview(null);
+ if (imagePreviewUrlRef.current) {
+ URL.revokeObjectURL(imagePreviewUrlRef.current);
+ imagePreviewUrlRef.current = null;
+ }
+ }, []);
+
const handleOpenAttachment = useCallback(
async (message: ChatMessage, attachment: ChatAttachment) => {
if (!chatKey) return;
@@ -2589,6 +2604,20 @@ const Page: React.FC = () => {
? `${baseName.replace(/\.[^/.]+$/, "")}.txt`
: `${baseName}.txt`;
+ if (treatAsImage) {
+ const mime = inferImageMime(baseName);
+ const blob = new Blob([toSafeBlobPart(bytes)], {
+ type: mime,
+ });
+ const url = URL.createObjectURL(blob);
+ if (imagePreviewUrlRef.current) {
+ URL.revokeObjectURL(imagePreviewUrlRef.current);
+ }
+ imagePreviewUrlRef.current = url;
+ setImagePreview({ url, name: baseName });
+ return;
+ }
+
if (isTauriRuntime) {
const [
{ appDataDir, join },
@@ -2626,12 +2655,6 @@ const Page: React.FC = () => {
window.setTimeout(() => URL.revokeObjectURL(url), 1000);
return;
}
-
- const mime = inferImageMime(baseName);
- const blob = new Blob([toSafeBlobPart(bytes)], { type: mime });
- const url = URL.createObjectURL(blob);
- window.open(url, "_blank", "noopener");
- window.setTimeout(() => URL.revokeObjectURL(url), 1000);
} catch (error) {
log.error("Failed to open attachment", error);
showMiniDialog({
@@ -2644,6 +2667,15 @@ const Page: React.FC = () => {
[chatKey, inferImageMime, isTauriRuntime, showMiniDialog],
);
+ useEffect(() => {
+ return () => {
+ if (imagePreviewUrlRef.current) {
+ URL.revokeObjectURL(imagePreviewUrlRef.current);
+ imagePreviewUrlRef.current = null;
+ }
+ };
+ }, []);
+
const flushStreamingText = useCallback(() => {
if (streamingFlushTimerRef.current) {
window.clearTimeout(streamingFlushTimerRef.current);
@@ -3525,9 +3557,7 @@ const Page: React.FC = () => {
return new File(
[toSafeBlobPart(bytes)],
normalizedJpegAttachmentName(name),
- {
- type: "image/jpeg",
- },
+ { type: "image/jpeg" },
);
}),
);
@@ -4208,6 +4238,8 @@ const Page: React.FC = () => {
setSyncNotificationOpen={setSyncNotificationOpen}
syncNotification={syncNotification}
modelGateStatus={modelGateStatus}
+ imagePreview={imagePreview}
+ closeImagePreview={closeImagePreview}
/>
</>
);