fix(webui): separate file cards from media previews

This commit is contained in:
Xubin Ren committed 2026-10-24 23:55:10 +08:00
1 parent d6cc08f335
commit 0b22c1875a
21 files changed
+432 -44

No files matched your search

+31 -27
View File
@@ -1,5 +1,6 @@
import { useState, type ReactNode } from "react";
import { useTranslation } from "react-i18next";
import { Download } from "lucide-react";
import { cn } from "@/lib/utils";
import type { UIMediaAttachment } from "@/lib/types";
@@ -61,58 +62,61 @@ export function AttachmentTile({ attachment, className, inline = false, variant
);
}
const fileKind = attachment.kind === "file"
? fileKindForPath(attachment.name || attachment.url || "")
: attachment.kind;
const filePath = attachment.name || attachment.url?.split(/[?#]/, 1)[0] || "";
const fileKind = attachment.kind === "file" ? fileKindForPath(filePath) : attachment.kind;
const name = attachment.name || label;
const available = hasUrl && !failed;
const extension = attachment.name?.match(/\.(tar\.(?:gz|bz2|xz)|[a-z0-9]{1,12})$/i)?.[1];
const details = available ? extension?.toUpperCase() || label
: pending ? t("message.delivery.sending") : t("message.attachmentUnavailable", { defaultValue: "Attachment unavailable" });
const cardClassName = cn(
"not-prose flex w-72 min-w-0 max-w-full items-center gap-3 rounded-control",
"border border-border/60 bg-muted/40 px-3 py-2.5 text-sm text-muted-foreground",
variant === "compact" && "w-56 gap-2 px-2.5 py-2 text-xs",
className,
);
const body = (
<>
<FileReferenceIcon kind={fileKind} className="size-4" />
<span className="min-w-0 truncate">{attachment.name ?? label}</span>
<span className={cn("flex size-9 shrink-0 items-center justify-center rounded-compact bg-background/70", variant === "compact" && "size-8")}>
<FileReferenceIcon kind={fileKind} className={variant === "compact" ? "size-4" : "size-5"} />
</span>
<span className="min-w-0 flex-1">
<span className="block truncate font-medium text-foreground">{name}</span>
<span className="block break-words text-xs leading-4">{details}</span>
</span>
</>
);
if (hasUrl && !failed) {
if (available) {
return (
<a
href={attachment.url}
download={attachment.name ?? label}
title={attachment.name ?? undefined}
aria-label={label}
download={name}
title={name}
aria-label={t("message.downloadAttachment", { name })}
className={cn(
"flex max-w-[18rem] items-center gap-2 rounded-control",
"border border-border/60 bg-muted/40 px-3 py-2 text-xs text-muted-foreground",
cardClassName,
"transition-colors hover:bg-muted/55 hover:text-foreground",
variant === "compact" && "max-w-[14rem] rounded-xl px-2.5 py-1.5 text-[11.5px]",
className,
"focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring focus-visible:ring-offset-2 focus-visible:ring-offset-background",
)}
>
{body}
<Download aria-hidden strokeWidth={1.75} className="size-4 shrink-0" />
</a>
);
}
const Frame = inline ? "span" : "div";
return (
<div
className={cn(
"flex max-w-[18rem] items-center gap-2 rounded-control",
"border border-border/60 bg-muted/35 px-3 py-2 text-xs text-muted-foreground",
variant === "compact" && "max-w-[14rem] rounded-xl px-2.5 py-1.5 text-[11.5px]",
className,
)}
title={attachment.name ?? undefined}
aria-label={label}
>
<Frame className={cardClassName} title={name} aria-label={attachment.name ? `${label}: ${name}` : label}>
{body}
<span className="text-xs text-muted-foreground">
{pending ? t("message.delivery.sending") : t("message.attachmentUnavailable", { defaultValue: "Attachment unavailable" })}
</span>
{attachment.kind === "video" && failed && !pending ? (
<button type="button" onClick={() => setFailedUrl(undefined)}
className="shrink-0 rounded-sm px-1 text-foreground underline-offset-2 hover:underline focus-visible:outline focus-visible:outline-2">
{t("common.retry")}
</button>
) : null}
</div>
</Frame>
);
}
+43 -1
View File
@@ -1,5 +1,5 @@
import { useEffect, useLayoutEffect, useRef, useState, type KeyboardEvent, type MouseEvent, type HTMLAttributes } from "react";
import { File, FileCode2, FileImage, FileJson2, FileText, FileVideo2, type LucideIcon } from "lucide-react";
import { File, FileArchive, FileAudio, FileChartColumn, FileCode2, FileImage, FileJson2, FileSpreadsheet, FileText, FileVideo2, type LucideIcon } from "lucide-react";
import { useTranslation } from "react-i18next";
import { FileActions, useFilePreviewLoader } from "@/components/FileActions";
import { inferMediaKind } from "@/lib/media";
@@ -14,15 +14,20 @@ import { cn } from "@/lib/utils";
export type FileReferenceKind =
| "default"
| "archive"
| "audio"
| "css"
| "document"
| "html"
| "image"
| "javascript"
| "json"
| "markdown"
| "notebook"
| "presentation"
| "python"
| "react"
| "spreadsheet"
| "text"
| "typescript"
| "video";
@@ -232,6 +237,38 @@ export function fileKindForPath(path: string): FileReferenceKind {
return "default";
}
switch (ext) {
case "zip":
case "7z":
case "rar":
case "tar":
case "gz":
case "bz2":
case "xz":
case "tgz":
return "archive";
case "mp3":
case "wav":
case "ogg":
case "m4a":
case "flac":
case "aac":
return "audio";
case "pdf":
case "doc":
case "docx":
case "odt":
case "rtf":
return "document";
case "xls":
case "xlsx":
case "csv":
case "tsv":
case "ods":
return "spreadsheet";
case "ppt":
case "pptx":
case "odp":
return "presentation";
case "avif":
return "image";
case "py":
@@ -273,15 +310,20 @@ export function fileKindForPath(path: string): FileReferenceKind {
const FILE_ICONS = {
default: File,
archive: FileArchive,
audio: FileAudio,
css: FileCode2,
document: FileText,
html: FileCode2,
image: FileImage,
javascript: FileCode2,
json: FileJson2,
markdown: FileText,
notebook: FileCode2,
presentation: FileChartColumn,
python: FileCode2,
react: FileCode2,
spreadsheet: FileSpreadsheet,
text: FileText,
typescript: FileCode2,
video: FileVideo2,
+17 -7
View File
@@ -651,32 +651,42 @@ function MessageMedia({
if (media.length === 0) return null;
const images: UIImage[] = [];
const seen = new Set<string>();
const nonImages: UIMediaAttachment[] = [];
const videos: UIMediaAttachment[] = [];
const files: UIMediaAttachment[] = [];
for (const item of media) {
const normalized = toMediaAttachment(item);
if (normalized.kind === "image") {
if (normalized.url && (inlineImages.has(normalized.url) || seen.has(normalized.url))) continue;
if (normalized.url) seen.add(normalized.url);
images.push({ url: normalized.url, name: normalized.name });
} else if (normalized.kind === "video") {
videos.push(normalized);
} else {
nonImages.push(normalized);
files.push(normalized);
}
}
if (images.length === 0 && nonImages.length === 0) return null;
if (images.length === 0 && videos.length === 0 && files.length === 0) return null;
return (
<div
className={cn(
"mt-2 flex flex-wrap gap-2",
align === "right" ? "justify-end" : "justify-start",
"mt-2 flex min-w-0 max-w-full flex-col gap-2",
align === "right" ? "items-end" : "items-start",
)}
>
{images.length > 0 ? (
<ImageGallery images={images} align={align} size={align === "left" ? "large" : "compact"} />
) : null}
{nonImages.map((item, i) => (
<AttachmentTile key={`${item.kind}-${i}`} attachment={item} pending={pending} />
{videos.map((item, i) => (
<AttachmentTile key={`video-${i}`} attachment={item} pending={pending} className="my-0" />
))}
{files.length > 0 ? (
<div className={cn("flex w-full min-w-0 flex-wrap items-start gap-2", align === "right" && "justify-end")}>
{files.map((item, i) => (
<AttachmentTile key={`file-${i}`} attachment={item} pending={pending} />
))}
</div>
) : null}
</div>
);
}
+1
View File
@@ -2539,6 +2539,7 @@
"imageAttachment": "Image attachment",
"videoAttachment": "Video attachment",
"fileAttachment": "File attachment",
"downloadAttachment": "Download {{name}}",
"attachmentUnavailable": "Attachment unavailable",
"dataTable": "Data table",
"fileEditPreparing": "Preparing file edit…",
+1
View File
@@ -2157,6 +2157,7 @@
"imageAttachment": "Imagen adjunta",
"videoAttachment": "Archivo de vídeo",
"fileAttachment": "Archivo adjunto",
"downloadAttachment": "Descargar {{name}}",
"attachmentUnavailable": "Adjunto no disponible",
"dataTable": "Tabla de datos",
"fileEditPreparing": "Preparando la edición del archivo…",
+1
View File
@@ -2156,6 +2156,7 @@
"imageAttachment": "Pièce jointe image",
"videoAttachment": "Pièce jointe vidéo",
"fileAttachment": "Pièce jointe",
"downloadAttachment": "Télécharger {{name}}",
"attachmentUnavailable": "Pièce jointe indisponible",
"dataTable": "Tableau de données",
"fileEditPreparing": "Préparation de la modification du fichier…",
+1
View File
@@ -2156,6 +2156,7 @@
"imageAttachment": "Lampiran gambar",
"videoAttachment": "Lampiran video",
"fileAttachment": "Lampiran file",
"downloadAttachment": "Unduh {{name}}",
"attachmentUnavailable": "Lampiran tidak tersedia",
"dataTable": "Tabel data",
"fileEditPreparing": "Menyiapkan perubahan file…",
+1
View File
@@ -2156,6 +2156,7 @@
"imageAttachment": "画像の添付",
"videoAttachment": "動画の添付",
"fileAttachment": "ファイルの添付",
"downloadAttachment": "{{name}} をダウンロード",
"attachmentUnavailable": "添付ファイルを利用できません",
"dataTable": "データテーブル",
"fileEditPreparing": "ファイル編集を準備中…",
+1
View File
@@ -2156,6 +2156,7 @@
"imageAttachment": "이미지 첨부",
"videoAttachment": "동영상 첨부",
"fileAttachment": "파일 첨부",
"downloadAttachment": "{{name}} 다운로드",
"attachmentUnavailable": "첨부 파일을 사용할 수 없음",
"dataTable": "데이터 표",
"fileEditPreparing": "파일 편집 준비 중…",
+1
View File
@@ -2347,6 +2347,7 @@
"imageAttachment": "Anexo de imagem",
"videoAttachment": "Anexo de vídeo",
"fileAttachment": "Anexo de arquivo",
"downloadAttachment": "Baixar {{name}}",
"attachmentUnavailable": "Anexo indisponível",
"dataTable": "Tabela de dados",
"fileEditPreparing": "Preparando a edição do arquivo…",
+1
View File
@@ -2156,6 +2156,7 @@
"imageAttachment": "Tệp hình ảnh đính kèm",
"videoAttachment": "Tệp video đính kèm",
"fileAttachment": "Tệp đính kèm",
"downloadAttachment": "Tải xuống {{name}}",
"attachmentUnavailable": "Tệp đính kèm không khả dụng",
"dataTable": "Bảng dữ liệu",
"fileEditPreparing": "Đang chuẩn bị sửa tệp…",
+1
View File
@@ -2539,6 +2539,7 @@
"imageAttachment": "图片附件",
"videoAttachment": "视频附件",
"fileAttachment": "文件附件",
"downloadAttachment": "下载 {{name}}",
"attachmentUnavailable": "附件不可用",
"dataTable": "数据表",
"fileEditPreparing": "准备编辑文件…",
+1
View File
@@ -2156,6 +2156,7 @@
"imageAttachment": "圖片附件",
"videoAttachment": "影片附件",
"fileAttachment": "檔案附件",
"downloadAttachment": "下載 {{name}}",
"attachmentUnavailable": "附件無法使用",
"dataTable": "資料表",
"fileEditPreparing": "準備編輯檔案…",
+47
View File
@@ -0,0 +1,47 @@
import { render, screen } from "@testing-library/react";
import { describe, expect, it } from "vitest";
import { AttachmentTile } from "@/components/AttachmentTile";
describe("attachment download cards", () => {
it("keeps named download actions distinct and shows the file extension", () => {
render(<>
<AttachmentTile attachment={{ kind: "file", name: "猫咪图鉴完整包.zip", url: "/api/media/signed/archive" }} />
<AttachmentTile attachment={{ kind: "file", name: "source.tar.gz", url: "/api/media/signed/source" }} />
</>);
const archive = screen.getByRole("link", { name: "Download 猫咪图鉴完整包.zip" });
expect(archive).toHaveAttribute("download", "猫咪图鉴完整包.zip");
expect(archive).toHaveAttribute("href", "/api/media/signed/archive");
expect(archive).toHaveAttribute("title", "猫咪图鉴完整包.zip");
expect(archive).toHaveTextContent("ZIP");
expect(archive.querySelector(".lucide-download")).toHaveAttribute("aria-hidden", "true");
expect(screen.getByRole("link", { name: "Download source.tar.gz" })).toHaveTextContent("TAR.GZ");
});
it("changes a pending file to a download only after its URL arrives", () => {
const attachment = { kind: "file" as const, name: "report.pdf" };
const { rerender } = render(<AttachmentTile attachment={attachment} pending />);
expect(screen.getByText("Sending…")).toBeVisible();
expect(screen.queryByRole("link")).not.toBeInTheDocument();
rerender(<AttachmentTile attachment={{ ...attachment, url: "/api/media/signed/report" }} />);
expect(screen.getByRole("link", { name: "Download report.pdf" })).toHaveTextContent("PDF");
rerender(<AttachmentTile attachment={attachment} />);
expect(screen.getByText("Attachment unavailable")).toBeVisible();
expect(screen.queryByRole("link")).not.toBeInTheDocument();
});
it("keeps unnamed and extensionless attachments identifiable", () => {
render(<>
<AttachmentTile attachment={{ kind: "file", url: "/api/media/signed/archive.zip?signature=example#payload.txt" }} />
<AttachmentTile attachment={{ kind: "file", name: "LICENSE", url: "/api/media/signed/license" }} />
</>);
const unnamed = screen.getByRole("link", { name: "Download File attachment" });
expect(unnamed).toHaveAttribute("download", "File attachment");
expect(unnamed).toHaveTextContent("File attachment");
expect(unnamed.querySelector(".lucide-file-archive")).toBeInTheDocument();
expect(screen.getByRole("link", { name: "Download LICENSE" })).toHaveTextContent("File attachment");
});
});
+16 -4
View File
@@ -14,6 +14,7 @@ describe("shared file icons", () => {
["styles.css", "file-code2"],
["app.js", "file-code2"],
["app.ts", "file-code2"],
["app#draft.ts", "file-code2"],
["app.tsx", "file-code2"],
["script.py", "file-code2"],
["analysis.ipynb", "file-code2"],
@@ -22,7 +23,18 @@ describe("shared file icons", () => {
["notes.txt", "file-text"],
["build.log", "file-text"],
["demo.mp4", "file-video2"],
["archive.zip", "file"],
["https://files.example.com/demo.mp4?signature=abc#download.zip", "file-video2"],
["archive.zip", "file-archive"],
["backup.tar.gz", "file-archive"],
["voice.mp3", "file-audio"],
["recording.flac", "file-audio"],
["REPORT#2.PDF", "file-text"],
["proposal.docx", "file-text"],
["budget.xlsx", "file-spreadsheet"],
["results.csv", "file-spreadsheet"],
["slides.pptx", "file-chart-column"],
["slides.odp", "file-chart-column"],
["payload.bin", "file"],
])("uses a consistent monochrome file-family icon for %s", (path, icon) => {
const { container } = render(<FileReferenceIcon kind={fileKindForPath(path)} />);
const svg = container.querySelector("svg")!;
@@ -36,7 +48,7 @@ describe("shared file icons", () => {
expect(svg.querySelector("text, [fill], [stroke]")).toBeNull();
});
it.each(["chart.png", "index.html", "data.json", "script.py", "notes.md"])(
it.each(["chart.png", "index.html", "data.json", "script.py", "notes.md", "archive.zip", "report.pdf", "budget.xlsx", "slides.pptx", "song.mp3"])(
"reuses the same glyph for %s in replies, tabs and attachments without changing actions", (path) => {
const open = vi.fn();
render(<>
@@ -48,12 +60,12 @@ describe("shared file icons", () => {
</>);
const reference = screen.getByRole("button", { name: path });
const tab = screen.getByRole("tab", { name: path });
const attachment = screen.getByRole("link", { name: "File attachment" });
const attachment = screen.getByRole("link", { name: `Download ${path}` });
const glyph = reference.querySelector("svg")!.innerHTML;
expect(tab.querySelector("svg")!.innerHTML).toBe(glyph);
expect(attachment.querySelector("svg")!.innerHTML).toBe(glyph);
expect(tab.querySelector("svg")).toHaveClass("size-3.5");
expect(attachment.querySelector("svg")).toHaveClass("size-4");
expect(attachment.querySelector("svg")).toHaveClass("size-5");
expect(tab.querySelector("svg")).not.toHaveClass("translate-y-[0.12em]");
expect(attachment.querySelector("svg")).not.toHaveClass("translate-y-[0.12em]");
expect(attachment).toHaveAttribute("href", `/download/${path}`);
@@ -291,7 +291,7 @@ describe("MarkdownTextRenderer", () => {
it("renders markdown links with file-looking names as file attachments", () => {
render(<MarkdownTextRenderer>![index.html](/api/media/sig/html)</MarkdownTextRenderer>);
expect(screen.getByLabelText("File attachment")).toHaveTextContent("index.html");
expect(screen.getByRole("link", { name: "Download index.html" })).toHaveTextContent("index.html");
expect(screen.queryByRole("img", { name: "index.html" })).not.toBeInTheDocument();
});
+2 -2
View File
@@ -1268,7 +1268,7 @@ describe("MessageBubble", () => {
const { container } = render(<MessageBubble message={message} />);
expect(screen.getByLabelText("File attachment")).toHaveTextContent("index.html");
expect(screen.getByRole("link", { name: "Download index.html" })).toHaveTextContent("index.html");
expect(container.querySelector("img")).not.toBeInTheDocument();
});
@@ -1291,7 +1291,7 @@ describe("MessageBubble", () => {
expect(screen.getByRole("button", { name: /view image: growth.svg/i })).toBeInTheDocument();
expect(container.querySelector('img[src="/api/media/sig/svg"]')).toBeInTheDocument();
expect(screen.queryByLabelText("File attachment")).not.toBeInTheDocument();
expect(screen.queryByRole("link", { name: "Download growth.svg" })).not.toBeInTheDocument();
});
});