feat(webui): refine attachment galleries and file cards (#6457)

* feat(webui): refine attachment galleries and file cards

* fix(webui): align attachment tests and Escape handling
This commit is contained in:
chengyongru authored and GitHub committed 2026-10-25 22:39:44 +08:00
1 parent 44a7ef53ce
commit eed7b47753
19 files changed
+660 -255

No files matched your search

+73
View File
@@ -0,0 +1,73 @@
import { useState, type ReactNode } from "react";
import { FileText, ImageIcon, Video } from "lucide-react";
import { useTranslation } from "react-i18next";
import { Popover, PopoverContent, PopoverTrigger } from "@/components/ui/popover";
import { Tooltip, TooltipContent, TooltipProvider, TooltipTrigger } from "@/components/ui/tooltip";
import type { UIMediaKind } from "@/lib/types";
import { cn } from "@/lib/utils";
export const attachmentCardActionClassName = "absolute right-0 top-0 grid h-11 w-11 place-items-center rounded-full focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-inset focus-visible:ring-ring";
/** The card owns only its information surface; callers own removal, download, and status. */
export function AttachmentCard({ name, description, children, action, invalid = false }: {
name: string;
description?: string;
children: ReactNode;
action?: ReactNode;
invalid?: boolean;
}) {
const [detailsOpen, setDetailsOpen] = useState(false);
const [hintOpen, setHintOpen] = useState(false);
const changeDetailsOpen = (open: boolean) => { setDetailsOpen(open); setHintOpen(false); };
const details = <>
<span className="block font-medium">{name}</span>
{description ? <span className="block text-muted-foreground">{description}</span> : null}
</>;
return <span className={cn(
"relative block h-24 w-24 max-w-full shrink-0 rounded-control border transition-colors motion-reduce:transition-none",
invalid ? "border-destructive/40 bg-destructive/5 text-destructive" : "border-border/70 bg-muted/35",
)}>
<TooltipProvider>
<Tooltip open={hintOpen && !detailsOpen} onOpenChange={setHintOpen}>
<Popover open={detailsOpen} onOpenChange={changeDetailsOpen}>
<PopoverTrigger asChild>
<TooltipTrigger asChild>
<button type="button" aria-label={name} aria-description={description}
onKeyDown={(event) => {
// The trigger retains focus while details are open, including during the layer handoff.
if (event.key === "Escape" && detailsOpen) {
event.preventDefault();
event.stopPropagation();
changeDetailsOpen(false);
}
}}
className="absolute inset-0 overflow-hidden rounded-[inherit] focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-inset focus-visible:ring-ring">
{children}
</button>
</TooltipTrigger>
</PopoverTrigger>
<PopoverContent side="top" aria-label={name}
onOpenAutoFocus={(event) => event.preventDefault()}
className="w-max max-w-[min(20rem,calc(100vw-2rem))] break-words px-3 py-1.5 text-caption">
{details}
</PopoverContent>
</Popover>
<TooltipContent side="top" className="max-w-[min(20rem,calc(100vw-2rem))] break-words">{details}</TooltipContent>
</Tooltip>
</TooltipProvider>
{action}
</span>;
}
export function AttachmentTypeFace({ name, kind = "file" }: { name: string; kind?: UIMediaKind }) {
const { t } = useTranslation();
const type = name.match(/\.(tar\.(?:gz|bz2|xz)|[a-z0-9]{1,12})$/i)?.[1].toUpperCase()
|| t(kind === "image" ? "message.imageAttachment" : kind === "video" ? "message.videoAttachment" : "message.fileAttachment");
const Icon = kind === "image" ? ImageIcon : kind === "video" ? Video : FileText;
return <span className="flex h-full w-full flex-col items-center justify-center gap-2" aria-hidden>
<Icon className="h-7 w-7 text-muted-foreground" strokeWidth={1.25} />
<span className="max-w-full truncate px-2 text-[10px] font-semibold tracking-wide text-muted-foreground">{type}</span>
</span>;
}
+19 -53
View File
@@ -7,7 +7,7 @@ import type { UIMediaAttachment } from "@/lib/types";
import { ImageThumbnail } from "@/components/ImageGallery";
import { ImageLightbox } from "@/components/ImageLightbox";
import { useRegisterInlineImage } from "@/components/InlineImageContext";
import { FileReferenceIcon, fileKindForPath } from "@/components/FileReferenceChip";
import { AttachmentCard, AttachmentTypeFace, attachmentCardActionClassName } from "@/components/AttachmentCard";
interface AttachmentTileProps {
attachment: UIMediaAttachment;
@@ -63,61 +63,27 @@ export function AttachmentTile({ attachment, className, inline = false, variant
}
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 = (
<>
<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>
</>
);
const status = available ? undefined : pending ? t("message.delivery.sending") : t("message.attachmentUnavailable");
const download = available ? <a href={attachment.url} download={name} title={name}
aria-label={t("message.downloadAttachment", { name })}
className={cn(attachmentCardActionClassName, "text-muted-foreground hover:text-foreground")}>
<Download aria-hidden strokeWidth={1.75} className="size-4" />
</a> : undefined;
if (available) {
return (
<a
href={attachment.url}
download={name}
title={name}
aria-label={t("message.downloadAttachment", { name })}
className={cn(
cardClassName,
"transition-colors hover:bg-muted/55 hover:text-foreground",
"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 (
<Frame className={cardClassName} title={name} aria-label={attachment.name ? `${label}: ${name}` : label}>
{body}
{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}
</Frame>
);
return <span data-file-attachment className={cn("not-prose inline-flex w-24 max-w-full shrink-0 flex-col gap-1 align-top", className)}>
<AttachmentCard name={name} description={status} action={download}>
<AttachmentTypeFace name={filePath} kind={attachment.kind} />
</AttachmentCard>
{status ? <span className="break-words text-center text-[11px] leading-4 text-muted-foreground">{status}</span> : null}
{attachment.kind === "video" && failed && !pending ? (
<button type="button" onClick={() => setFailedUrl(undefined)}
className="min-h-11 rounded-sm px-1 text-xs text-foreground underline-offset-2 hover:underline focus-visible:outline focus-visible:outline-2">
{t("common.retry")}
</button>
) : null}
</span>;
}
function AttachmentFrame({
+72 -19
View File
@@ -1,8 +1,9 @@
import { useState } from "react";
import { useLayoutEffect, useRef, useState, type CSSProperties } from "react";
import { ImageIcon } from "lucide-react";
import { useTranslation } from "react-i18next";
import { ImageLightbox } from "@/components/ImageLightbox";
import { IMAGE_GAP, imageFrameRatio, layoutImageRows, type ImageDimensions } from "@/lib/image-gallery-layout";
import type { UIImage } from "@/lib/types";
import { cn } from "@/lib/utils";
@@ -14,20 +15,64 @@ export function ImageGallery({ images, align = "left", size = "large" }: {
}) {
const { t } = useTranslation();
const [index, setIndex] = useState<number | null>(null);
const [dimensions, setDimensions] = useState<Record<string, ImageDimensions | null>>({});
const [width, setWidth] = useState(0);
const container = useRef<HTMLSpanElement>(null);
const viewable = images.filter((image) => image.url);
const multiple = images.length > 1;
const visible = images.slice(0, 4);
const measured = visible.map((image) => image.url ? dimensions[image.url] : null);
const ready = measured.every((image) => image !== undefined);
const maxWidth = size === "large" ? 448 : 360;
const maxHeight = visible.length === 1 ? (size === "large" ? 352 : 320) : (size === "large" ? 256 : 224);
const single = visible.length === 1 ? measured[0] : null;
const preferredWidth = single ? Math.min(maxWidth, single.width, maxHeight * imageFrameRatio(single)) : maxWidth;
useLayoutEffect(() => {
const element = container.current;
if (!element) return;
const measure = () => setWidth(element.getBoundingClientRect().width);
measure();
const observer = new ResizeObserver(measure);
observer.observe(element);
return () => observer.disconnect();
}, [preferredWidth]);
const layoutWidth = Math.min(width || preferredWidth, preferredWidth);
const rows = layoutImageRows(
ready ? measured : visible.map(() => null), layoutWidth,
size === "large" ? 176 : 144, maxHeight,
);
let top = 0;
const tiles = rows.flatMap((row) => {
const rowWidth = row.widths.reduce((sum, item) => sum + item, IMAGE_GAP * (row.widths.length - 1));
let left = align === "right" ? layoutWidth - rowWidth : 0;
const items = row.widths.map((tileWidth, offset) => {
const tile = { position: row.start + offset, frame: { width: tileWidth, height: row.height, left, top } };
left += tileWidth + IMAGE_GAP;
return tile;
});
top += row.height + IMAGE_GAP;
return items;
});
const remember = (url: string, value: ImageDimensions | null) => setDimensions((current) => {
const previous = current[url];
if (previous === value || (previous && value && previous.width === value.width && previous.height === value.height)) return current;
return { ...current, [url]: value };
});
return <>
<span className={cn(
"max-w-full gap-2",
multiple && size === "large" ? "grid w-[28rem] grid-cols-2" : "flex flex-wrap items-end",
align === "right" ? "ml-auto justify-end" : "mr-auto justify-start",
)}>
{visible.map((image, position) => {
<span ref={container} data-image-gallery className={cn(
"relative block max-w-full",
align === "right" ? "ml-auto" : "mr-auto",
)} style={{ width: preferredWidth, height: Math.max(0, top - IMAGE_GAP) }}>
{tiles.map(({ position, frame }) => {
const image = visible[position];
const remaining = images.length - visible.length;
const overflow = position === visible.length - 1 && remaining > 0;
return <ImageThumbnail key={`${image.url ?? image.name}-${position}`}
image={image} size={multiple && size === "large" ? "grid" : size}
image={image} size={size} frame={frame}
onLoad={(value) => { if (image.url) remember(image.url, value); }}
onError={() => { if (image.url) remember(image.url, null); }}
label={overflow ? t("lightbox.viewAll", { count: images.length }) : undefined}
onOpen={image.url || (overflow && viewable.length) ? () => setIndex(Math.max(0, viewable.indexOf(image))) : undefined}
overlay={overflow ? `+${remaining}` : undefined} />;
@@ -38,31 +83,39 @@ export function ImageGallery({ images, align = "left", size = "large" }: {
</>;
}
export function ImageThumbnail({ image, size = "large", onOpen, label, overlay, onError }: {
export function ImageThumbnail({ image, size = "large", frame, onOpen, label, overlay, onLoad, onError }: {
image: UIImage;
size?: "compact" | "large" | "grid";
size?: "compact" | "large";
frame?: ImageDimensions & { left: number; top: number };
onOpen?: () => void;
label?: string;
overlay?: string;
onLoad?: (dimensions: ImageDimensions) => void;
onError?: () => void;
}) {
const { t } = useTranslation();
const [failed, setFailed] = useState(false);
const classes = cn(
"relative block max-w-full overflow-hidden rounded-control border border-border/60 bg-muted/25",
size === "large" ? "w-[min(100%,28rem)]" : size === "grid" ? "aspect-[8/5] w-full" : "h-24 w-24",
"relative block max-w-full shrink-0 overflow-hidden rounded-control bg-muted/25 ring-1 ring-inset ring-border/60",
!frame && (size === "large" ? "w-[min(100%,28rem)]" : "w-48"),
);
const style: CSSProperties | undefined = frame ? { ...frame, position: "absolute" } : undefined;
const unavailable = t("message.attachmentUnavailable");
const content = image.url && !failed ? <img src={image.url} alt={image.name ?? ""}
loading="lazy" decoding="async" draggable={false}
onLoad={(event) => {
const { naturalWidth, naturalHeight } = event.currentTarget;
onLoad?.({ width: naturalWidth, height: naturalHeight });
}}
onError={() => { setFailed(true); onError?.(); }}
className={cn("block w-full object-contain", size === "large" ? "h-auto max-h-[22rem]" : "h-full")} />
: <span className={cn("flex min-h-24 items-center justify-center gap-2 px-3 py-5 text-xs text-muted-foreground", size === "grid" && "h-full")}
aria-label={t("message.attachmentUnavailable")}>
className={cn("block w-full object-contain text-transparent", frame ? "h-full" : "h-auto max-h-[22rem]")} />
: <span className={cn("flex items-center justify-center gap-2 px-3 text-xs text-muted-foreground", frame ? "h-full" : "min-h-24 py-5")}
aria-label={image.name ? `${unavailable}: ${image.name}` : unavailable} title={image.name}>
<ImageIcon className="h-4 w-4 shrink-0" aria-hidden />
<span className="min-w-0 truncate">{image.name || t("message.imageAttachment")}</span>
<span className="min-w-0 truncate">{unavailable}</span>
</span>;
if (!onOpen || ((!image.url || failed) && !overlay)) return <span className={classes}>{content}</span>;
return <button type="button" onClick={onOpen}
if (!onOpen || ((!image.url || failed) && !overlay)) return <span className={classes} style={style}>{content}</span>;
return <button type="button" onClick={onOpen} style={style}
aria-label={label ?? (image.name ? `${t("lightbox.open")}: ${image.name}` : t("lightbox.open"))}
className={cn(classes, "cursor-zoom-in p-0 focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring focus-visible:ring-offset-2 focus-visible:ring-offset-background")}>
{content}
+17 -79
View File
@@ -59,9 +59,6 @@ import {
ChevronDown,
ChevronUp,
CornerDownRight,
FileText,
Video,
ImageIcon,
Loader2,
Quote,
Trash2,
@@ -71,6 +68,7 @@ import {
import { useTranslation } from "react-i18next";
import { Button } from "@/components/ui/button";
import { AttachmentCard, AttachmentTypeFace, attachmentCardActionClassName } from "@/components/AttachmentCard";
import { ComposerActionIcon, type ComposerActionState } from "@/components/thread/ComposerActionIcon";
import {
floatingItemClassName,
@@ -3397,85 +3395,25 @@ function AttachmentChip({
? normalizedHint(image.file.size, image.encodedBytes)
: formatBytes(image.file.size);
const isThumbnail = image.kind === "image" && image.status !== "error";
const tone =
image.status === "error"
? "border-destructive/40 bg-destructive/5 text-destructive"
: "border-border/70 bg-muted/60";
const error = image.status === "error" && image.error ? formatError(image.error) : null;
return (
<div
className={cn(
"group relative flex max-w-full shrink-0 items-center rounded-control border",
"transition-colors motion-reduce:transition-none",
isThumbnail ? "h-24 w-24" : "gap-2 px-2 py-1.5",
tone,
)}
title={isThumbnail ? `${image.file.name}\n${sizeLabel}` : undefined}
data-testid="composer-chip"
>
<div className={cn(
"relative shrink-0 overflow-hidden bg-background",
isThumbnail ? "h-full w-full rounded-[inherit]" : "h-10 w-10 rounded-md",
)}>
{image.kind === "image" && image.previewUrl ? (
<img
src={image.previewUrl}
alt={isThumbnail ? image.file.name : ""}
loading="eager"
draggable={false}
className="h-full w-full object-cover"
/>
) : (
<div className="flex h-full w-full items-center justify-center">
{image.kind === "image" ? (
<ImageIcon className="h-4 w-4 text-muted-foreground" aria-hidden />
) : image.kind === "video" ? (
<Video className="h-4 w-4 text-muted-foreground" aria-hidden />
) : (
<FileText className="h-4 w-4 text-muted-foreground" aria-hidden />
)}
</div>
)}
{image.status === "encoding" ? (
<div
className="absolute inset-0 flex items-center justify-center bg-background/60"
aria-label={labelEncoding}
>
<Loader2 className="h-4 w-4 animate-spin motion-reduce:animate-none" aria-hidden />
</div>
) : null}
</div>
{!isThumbnail ? (
<div className="flex min-w-0 flex-col text-[11.5px] leading-4">
<span className="max-w-[min(14rem,calc(100vw-8rem))] truncate font-medium" title={image.file.name}>
{image.file.name}
<div className="flex w-24 max-w-full shrink-0 flex-col gap-1" data-testid="composer-chip">
<AttachmentCard name={image.file.name} description={sizeLabel} invalid={!!error}
action={<button type="button" ref={registerRef} onClick={onRemove} onKeyDown={onKeyDown}
aria-label={labelRemove} aria-description={image.file.name} title={labelRemove}
className={cn(attachmentCardActionClassName, "group/remove focus-visible:bg-black/50 focus-visible:ring-white")}>
<span className="grid h-5 w-5 place-items-center rounded-full bg-black/65 text-white group-hover/remove:bg-black/80">
<X className="h-3 w-3" aria-hidden />
</span>
<span className="truncate text-muted-foreground">
{image.status === "error" && image.error
? formatError(image.error)
: sizeLabel}
</span>
</div>
) : null}
<button
type="button"
ref={registerRef}
onClick={onRemove}
onKeyDown={onKeyDown}
aria-label={labelRemove}
aria-description={image.file.name}
title={labelRemove}
className={cn(
"grid flex-none place-items-center rounded-full focus-visible:outline-none focus-visible:ring-2",
isThumbnail
? "group/remove absolute right-0 top-0 h-11 w-11 focus-visible:bg-black/50 focus-visible:ring-inset focus-visible:ring-white"
: "ml-1 h-5 w-5 text-muted-foreground/80 hover:text-foreground focus-visible:ring-foreground/30",
)}
>
<span className={cn(isThumbnail && "grid h-5 w-5 place-items-center rounded-full bg-black/65 text-white group-hover/remove:bg-black/80")}>
<X className={isThumbnail ? "h-3 w-3" : "h-3.5 w-3.5"} aria-hidden />
</span>
</button>
</button>}>
{isThumbnail && image.previewUrl ? <img src={image.previewUrl} alt={image.file.name} loading="eager" draggable={false}
className="h-full w-full object-cover" /> : <AttachmentTypeFace name={image.file.name} kind={image.kind} />}
{image.status === "encoding" ? <span className="absolute inset-0 flex items-center justify-center bg-background/60" aria-label={labelEncoding}>
<Loader2 className="h-4 w-4 animate-spin motion-reduce:animate-none" aria-hidden />
</span> : null}
</AttachmentCard>
{error ? <span className="break-words text-center text-[11px] leading-4 text-destructive">{error}</span> : null}
</div>
);
}