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:
1 parent
44a7ef53ce
commit
eed7b47753
19 files changed
+660
-255
No files matched your search
@@ -149,3 +149,35 @@ async def test_mixed_media_replay_keeps_uploaded_cache_and_borrowed_freshness(tm
|
||||
assert bytes(served.body) == expected
|
||||
assert served.headers["Cache-Control"] == cache
|
||||
assert sorted(path.name for path in media.iterdir()) == ["borrowed.png", "upload.png"]
|
||||
|
||||
|
||||
@pytest.mark.parametrize("role", ["assistant", "user"])
|
||||
def test_replayed_media_keeps_missing_files_in_order_without_download_urls(tmp_path, monkeypatch, role):
|
||||
media = tmp_path / "media"
|
||||
media.mkdir()
|
||||
first = media / "first.json"
|
||||
missing = media / "missing.txt"
|
||||
last = media / "last.pdf"
|
||||
first.write_bytes(b'{"synthetic":true}')
|
||||
last.write_bytes(b"synthetic pdf")
|
||||
paths = [str(path) for path in (first, missing, last)]
|
||||
gateway = WebUIMediaGateway(workspace_path=tmp_path, logger=Mock(), media_dir=lambda _: media)
|
||||
|
||||
def project():
|
||||
if role == "assistant":
|
||||
return gateway.augment_transcript_media(paths)
|
||||
return gateway.augment_transcript_user_media(paths, [], session_key="websocket:files")
|
||||
|
||||
with monkeypatch.context() as patch:
|
||||
patch.setattr(type(first), "read_bytes", lambda *_: pytest.fail("projection read file contents"))
|
||||
attachments = project()
|
||||
assert [item["name"] for item in attachments] == ["first.json", "missing.txt", "last.pdf"]
|
||||
assert attachments[1] == {"kind": "file", "name": "missing.txt", "url": ""}
|
||||
sig, payload = attachments[0]["url"].split("/")[-2:]
|
||||
assert bytes(gateway.serve_signed_media(sig, payload).body) == b'{"synthetic":true}'
|
||||
assert attachments[2]["url"]
|
||||
|
||||
last.unlink()
|
||||
refreshed = project()
|
||||
assert [item["name"] for item in refreshed] == [item["name"] for item in attachments]
|
||||
assert refreshed[2]["url"] == ""
|
||||
@@ -184,17 +184,16 @@ def signed_media_attachments(
|
||||
*,
|
||||
sign_path: SignedMediaPath,
|
||||
) -> list[dict[str, Any]]:
|
||||
"""Map persisted media paths to WebUI attachment dicts with fresh signed URLs."""
|
||||
"""Keep every attachment in order, signing only files available at projection time."""
|
||||
out: list[dict[str, Any]] = []
|
||||
for pstr in paths:
|
||||
path = Path(pstr)
|
||||
att = sign_path(path)
|
||||
if att is None:
|
||||
continue
|
||||
url = att.get("url")
|
||||
if not url:
|
||||
continue
|
||||
name = att.get("name") or path.name
|
||||
try:
|
||||
att = sign_path(path) if path.is_file() else None
|
||||
except OSError:
|
||||
att = None
|
||||
name = (att.get("name") if att else None) or path.name
|
||||
url = (att.get("url") if att else None) or ""
|
||||
out.append({"kind": media_attachment_kind(name), "url": url, "name": name})
|
||||
return out
|
||||
|
||||
|
||||
@@ -96,9 +96,14 @@ class WebUIMediaGateway:
|
||||
media: list[dict[str, Any]] = []
|
||||
for raw in paths:
|
||||
path = Path(raw)
|
||||
if raw in local:
|
||||
url = self.local_attachment_url(raw, session_key=session_key) if path.is_file() else ""
|
||||
else:
|
||||
url = sign_media_path(path, secret=self.secret, media_dir=self._media_dir) or ""
|
||||
try:
|
||||
if not path.is_file():
|
||||
url = ""
|
||||
elif raw in local:
|
||||
url = self.local_attachment_url(raw, session_key=session_key)
|
||||
else:
|
||||
url = sign_media_path(path, secret=self.secret, media_dir=self._media_dir) or ""
|
||||
except OSError:
|
||||
url = ""
|
||||
media.append({"kind": media_attachment_kind(path.name), "name": path.name, "url": url})
|
||||
return media
|
||||
@@ -26,6 +26,26 @@ async function bounds(locator: Locator) {
|
||||
return box!;
|
||||
}
|
||||
|
||||
async function expectFileDetails(page: Page, card: Locator, filename: string, width: number, description?: string) {
|
||||
const info = card.getByRole("button", { name: filename, exact: true });
|
||||
await info.hover();
|
||||
await expect(page.getByRole("tooltip")).toContainText(filename);
|
||||
await info.click();
|
||||
const details = page.getByRole("dialog", { name: filename, exact: true });
|
||||
const name = details.getByText(filename, { exact: true });
|
||||
await expect(name).toBeVisible();
|
||||
if (description) await expect(details.getByText(description, { exact: true })).toBeVisible();
|
||||
const box = await bounds(details);
|
||||
expect(box.x).toBeGreaterThanOrEqual(0);
|
||||
expect(box.x + box.width).toBeLessThanOrEqual(width);
|
||||
expect(await name.evaluate((element) => element.scrollWidth <= element.clientWidth)).toBe(true);
|
||||
expect(await details.evaluate((element) => element.scrollHeight <= element.clientHeight)).toBe(true);
|
||||
await page.keyboard.press("Escape");
|
||||
await expect(details).toHaveCount(0);
|
||||
await expect(info).toBeFocused();
|
||||
await page.mouse.move(0, 0);
|
||||
}
|
||||
|
||||
for (const width of [1024, 360]) {
|
||||
for (const theme of ["light", "dark"]) {
|
||||
test(`mixed attachments stay compact, aligned and readable at ${width}px in ${theme}`, async ({ page }, testInfo) => {
|
||||
@@ -44,16 +64,19 @@ for (const width of [1024, 360]) {
|
||||
|
||||
for (const role of ["Assistant", "User"]) {
|
||||
const region = page.getByRole("region", { name: `${role} mixed attachments`, exact: true });
|
||||
const card = region.locator("a[download]");
|
||||
const card = region.locator("[data-file-attachment]");
|
||||
await expect(card).toHaveCount(1);
|
||||
const file = await bounds(card);
|
||||
const regionBox = await bounds(region);
|
||||
const imageBoxes = await region.locator("img").evaluateAll((images) => images.map((image) => {
|
||||
const rect = image.getBoundingClientRect();
|
||||
return { bottom: rect.bottom, left: rect.left, right: rect.right };
|
||||
const { naturalWidth, naturalHeight } = image as HTMLImageElement;
|
||||
return { bottom: rect.bottom, left: rect.left, right: rect.right, naturalWidth, naturalHeight };
|
||||
}));
|
||||
await testInfo.attach(`${role} geometry`, { body: JSON.stringify({ file, region: regionBox, images: imageBoxes }, null, 2), contentType: "application/json" });
|
||||
expect(file.height, `${role} file must not stretch to the image row height`).toBeLessThanOrEqual(80);
|
||||
expect(file.width, `${role} file card keeps its compact width`).toBe(96);
|
||||
expect(file.height, `${role} file card must not stretch to the image row height`).toBe(96);
|
||||
for (const image of imageBoxes) expect(image).toMatchObject({ naturalWidth: 320, naturalHeight: 200 });
|
||||
expect(file.y, `${role} file belongs below all images`).toBeGreaterThanOrEqual(Math.max(...imageBoxes.map((image) => image.bottom)));
|
||||
if (role === "Assistant") {
|
||||
expect(Math.abs(file.x - regionBox.x)).toBeLessThanOrEqual(1);
|
||||
@@ -63,15 +86,15 @@ for (const width of [1024, 360]) {
|
||||
expect(Math.abs(file.x + file.width - right)).toBeLessThanOrEqual(1);
|
||||
expect(Math.abs(Math.max(...imageBoxes.map((image) => image.right)) - right)).toBeLessThanOrEqual(2);
|
||||
}
|
||||
await expect(card).toHaveAccessibleName(`${chinese ? "下载" : "Download"} archive.zip`);
|
||||
await expect(card.getByRole("link")).toHaveAccessibleName(`${chinese ? "下载" : "Download"} archive.zip`);
|
||||
await expect(card.getByText("ZIP", { exact: true })).toBeVisible();
|
||||
}
|
||||
|
||||
const files = page.getByRole("region", { name: "Multiple files and long names" }).locator("a[download]");
|
||||
const files = page.getByRole("region", { name: "Multiple files and long names" }).locator("[data-file-attachment]");
|
||||
await expect(files).toHaveCount(3);
|
||||
const userFiles = page.getByRole("region", { name: "User multiple files", exact: true });
|
||||
const userBubble = await bounds(userFiles.locator(":scope > div"));
|
||||
const userCards = userFiles.locator("a[download]");
|
||||
const userCards = userFiles.locator("[data-file-attachment]");
|
||||
await expect(userCards).toHaveCount(3);
|
||||
const userCardBoxes = await Promise.all((await userCards.all()).map(bounds));
|
||||
await testInfo.attach("User multiple files geometry", { body: JSON.stringify({ bubble: userBubble, files: userCardBoxes }, null, 2), contentType: "application/json" });
|
||||
@@ -79,36 +102,47 @@ for (const width of [1024, 360]) {
|
||||
expect(box.x, "user file stays inside its message bubble").toBeGreaterThanOrEqual(userBubble.x);
|
||||
expect(box.x + box.width, "user file stays inside its message bubble").toBeLessThanOrEqual(userBubble.x + userBubble.width + 1);
|
||||
}
|
||||
for (const card of await page.locator("a[download]").all()) {
|
||||
const availableCards = page.locator("[data-file-attachment]").filter({ has: page.locator("a[download]") });
|
||||
for (const card of await availableCards.all()) {
|
||||
const box = await bounds(card);
|
||||
expect(box.height).toBeLessThanOrEqual(80);
|
||||
expect(box.width).toBe(96);
|
||||
expect(box.height).toBe(96);
|
||||
expect(box.x).toBeGreaterThanOrEqual(0);
|
||||
expect(box.x + box.width).toBeLessThanOrEqual(width);
|
||||
const icon = card.locator("svg.lucide-download");
|
||||
const download = card.locator("a[download]");
|
||||
const target = await bounds(download);
|
||||
expect(target.width).toBe(44);
|
||||
expect(target.height).toBe(44);
|
||||
expect(target.x).toBeGreaterThanOrEqual(box.x);
|
||||
expect(target.x + target.width).toBeLessThanOrEqual(box.x + box.width);
|
||||
expect(target.y).toBeGreaterThanOrEqual(box.y);
|
||||
expect(target.y + target.height).toBeLessThanOrEqual(box.y + box.height);
|
||||
const icon = download.locator("svg.lucide-download");
|
||||
await expect(icon).toBeVisible();
|
||||
const iconBox = await bounds(icon);
|
||||
expect(iconBox.width).toBeGreaterThanOrEqual(12);
|
||||
expect(iconBox.x).toBeGreaterThanOrEqual(box.x);
|
||||
expect(iconBox.x + iconBox.width).toBeLessThanOrEqual(box.x + box.width);
|
||||
expect(iconBox.y).toBeGreaterThanOrEqual(box.y);
|
||||
expect(iconBox.y + iconBox.height).toBeLessThanOrEqual(box.y + box.height);
|
||||
expect(iconBox.x).toBeGreaterThanOrEqual(target.x);
|
||||
expect(iconBox.x + iconBox.width).toBeLessThanOrEqual(target.x + target.width);
|
||||
expect(iconBox.y).toBeGreaterThanOrEqual(target.y);
|
||||
expect(iconBox.y + iconBox.height).toBeLessThanOrEqual(target.y + target.height);
|
||||
}
|
||||
for (const card of [files.nth(0), files.nth(1)]) {
|
||||
const name = card.getByText(/release-deliverables|项目交付资料/);
|
||||
await expect(name).toHaveCSS("text-overflow", "ellipsis");
|
||||
expect(await name.evaluate((element) => element.scrollWidth > element.clientWidth)).toBe(true);
|
||||
const nameBox = await bounds(name);
|
||||
expect(nameBox.x + nameBox.width).toBeLessThanOrEqual((await bounds(card.locator("svg.lucide-download"))).x);
|
||||
for (const [index, filename, type] of [
|
||||
[0, "release-deliverables-with-a-very-long-English-filename-for-layout-regression.zip", "ZIP"],
|
||||
[1, "项目交付资料与详细验收记录包含中英文的超长文件名称-final-review.pdf", "PDF"],
|
||||
] as const) {
|
||||
const card = files.nth(index);
|
||||
await expect(card.getByRole("button", { name: filename, exact: true })).toHaveText(type);
|
||||
await expectFileDetails(page, card, filename, width);
|
||||
}
|
||||
await expect(files.nth(1).getByText("PDF", { exact: true })).toBeVisible();
|
||||
await expect(files.nth(2)).toHaveAccessibleName(chinese ? "下载 文件附件" : "Download File attachment");
|
||||
await expect(files.nth(2).getByRole("link")).toHaveAccessibleName(chinese ? "下载 文件附件" : "Download File attachment");
|
||||
for (const [label, filename, status] of [
|
||||
["Pending attachment", "pending.zip", chinese ? "发送中…" : "Sending…"],
|
||||
["Unavailable attachment", "unavailable.pdf", chinese ? "附件不可用" : "Attachment unavailable"],
|
||||
]) {
|
||||
const region = page.getByRole("region", { name: label, exact: true });
|
||||
await expect(region.getByText(filename, { exact: true })).toBeVisible();
|
||||
await expect(region.getByText(status, { exact: true }).first()).toBeVisible();
|
||||
const card = region.locator("[data-file-attachment]");
|
||||
await expect(card.getByText(status, { exact: true })).toBeVisible();
|
||||
await expectFileDetails(page, card, filename, width, status);
|
||||
// A replay placeholder has no download capability until it has a URL.
|
||||
await expect(region.getByRole("link")).toHaveCount(0);
|
||||
}
|
||||
@@ -135,7 +169,22 @@ test("image lightbox and file download remain keyboard accessible", async ({ pag
|
||||
await page.keyboard.press("Escape");
|
||||
await expect(page.getByRole("dialog")).toHaveCount(0);
|
||||
await expect(firstImage).toBeFocused();
|
||||
for (let step = 0; step < 3; step++) await page.keyboard.press("Tab");
|
||||
for (const name of ["Blue study.svg", "Green study.svg"]) {
|
||||
await page.keyboard.press("Tab");
|
||||
await expect(region.getByRole("button", { name: `View image: ${name}`, exact: true })).toBeFocused();
|
||||
}
|
||||
await page.keyboard.press("Tab");
|
||||
const fileInfo = region.getByRole("button", { name: "archive.zip", exact: true });
|
||||
await expect(fileInfo).toBeFocused();
|
||||
expect(await fileInfo.evaluate((element) => element.matches(":focus-visible"))).toBe(true);
|
||||
await expect(page.getByRole("tooltip")).toContainText("archive.zip");
|
||||
await page.keyboard.press("Enter");
|
||||
const details = page.getByRole("dialog", { name: "archive.zip", exact: true });
|
||||
await expect(details.getByText("archive.zip", { exact: true })).toBeVisible();
|
||||
await page.keyboard.press("Escape");
|
||||
await expect(details).toHaveCount(0);
|
||||
await expect(fileInfo).toBeFocused();
|
||||
await page.keyboard.press("Tab");
|
||||
const downloadLink = region.getByRole("link", { name: "Download archive.zip", exact: true });
|
||||
await expect(downloadLink).toBeFocused();
|
||||
expect(await downloadLink.evaluate((element) => element.matches(":focus-visible"))).toBe(true);
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
import { expect, test, type Page } from "@playwright/test";
|
||||
import { expect, test, type Locator, type Page } from "@playwright/test";
|
||||
|
||||
async function imageFile(page: Page, name: string, background: string) {
|
||||
const data = await page.evaluate((fill) => {
|
||||
@@ -17,6 +17,26 @@ async function imageFile(page: Page, name: string, background: string) {
|
||||
return { name, mimeType: "image/png", buffer: Buffer.from(data, "base64") };
|
||||
}
|
||||
|
||||
async function expectAttachmentDetails(page: Page, chip: Locator, name: string, touch = false) {
|
||||
const info = chip.getByRole("button", { name, exact: true });
|
||||
const size = await info.getAttribute("aria-description");
|
||||
expect(size).toMatch(/^\d+(?:\.\d+)? (?:B|KiB|MiB)$/);
|
||||
if (touch) await info.tap();
|
||||
else {
|
||||
await info.hover();
|
||||
await expect(page.getByRole("tooltip")).toContainText(name);
|
||||
await expect(page.getByRole("tooltip")).toContainText(size!);
|
||||
await info.click();
|
||||
}
|
||||
const details = page.getByRole("dialog", { name, exact: true });
|
||||
await expect(details.getByText(name, { exact: true })).toBeVisible();
|
||||
await expect(details.getByText(size!, { exact: true })).toBeVisible();
|
||||
await page.keyboard.press("Escape");
|
||||
await expect(details).toHaveCount(0);
|
||||
await expect(info).toBeFocused();
|
||||
await page.mouse.move(0, 0);
|
||||
}
|
||||
|
||||
test.beforeEach(async ({ page }) => {
|
||||
await page.addInitScript(() => localStorage.setItem("nanobot.locale", "en"));
|
||||
await page.route("**/api/**", route => route.fulfill({ json: {} }));
|
||||
@@ -46,9 +66,8 @@ for (const { width, dark, variant } of [
|
||||
for (const name of ["white.png", "dark.png", "notes.png"]) {
|
||||
const image = page.getByRole("img", { name, exact: true });
|
||||
await expect(image).toBeVisible();
|
||||
expect(await image.evaluate(node => (node as HTMLImageElement).naturalWidth)).toBe(480);
|
||||
expect(await image.evaluate(node => ({ width: (node as HTMLImageElement).naturalWidth, height: (node as HTMLImageElement).naturalHeight }))).toEqual({ width: 480, height: 320 });
|
||||
const chip = chips.filter({ has: image });
|
||||
await expect(chip).toHaveAttribute("title", new RegExp(`^${name}\\n`));
|
||||
const box = (await chip.boundingBox())!;
|
||||
expect(box.width).toBe(96);
|
||||
expect(box.height).toBe(96);
|
||||
@@ -61,28 +80,33 @@ for (const { width, dark, variant } of [
|
||||
expect(target.height).toBeGreaterThanOrEqual(44);
|
||||
expect(target.x + target.width).toBeCloseTo(box.x + box.width - 1);
|
||||
expect(target.y).toBeCloseTo(box.y + 1);
|
||||
await expectAttachmentDetails(page, chip, name, width < 640);
|
||||
}
|
||||
const document = chips.filter({ hasText: "report.pdf" });
|
||||
await expect(document).toContainText("B");
|
||||
expect((await document.boundingBox())!.height).toBeLessThan(96);
|
||||
const document = chips.filter({ has: page.getByRole("button", { name: "report.pdf", exact: true }) });
|
||||
await expect(document).toHaveText("PDF");
|
||||
await expect(document.getByRole("button", { name: "report.pdf", exact: true })).toHaveAccessibleDescription(`${files[3].buffer.byteLength} B`);
|
||||
const documentBox = (await document.boundingBox())!;
|
||||
expect(documentBox.width).toBe(96);
|
||||
expect(documentBox.height).toBe(96);
|
||||
await expectAttachmentDetails(page, document, "report.pdf", width < 640);
|
||||
expect(await page.evaluate(() => window.document.documentElement.scrollWidth)).toBe(width);
|
||||
await page.getByRole("textbox").fill("Compare these images with the report.");
|
||||
const screenshot = testInfo.outputPath("composer-attachments.png");
|
||||
await page.locator("main").screenshot({ path: screenshot });
|
||||
await testInfo.attach("composer-attachments", { path: screenshot, contentType: "image/png" });
|
||||
|
||||
const whiteRemove = chips.filter({ has: page.getByRole("img", { name: "white.png", exact: true }) }).getByRole("button");
|
||||
const whiteRemove = chips.filter({ has: page.getByRole("img", { name: "white.png", exact: true }) }).getByRole("button", { name: "Remove attachment", exact: true });
|
||||
// Tap outside the visible circle, but inside the larger touch target.
|
||||
if (width < 640) await whiteRemove.tap({ position: { x: 6, y: 22 } });
|
||||
else await whiteRemove.click();
|
||||
await expect(chips).toHaveCount(3);
|
||||
const darkRemove = chips.filter({ has: page.getByRole("img", { name: "dark.png", exact: true }) }).getByRole("button");
|
||||
const darkRemove = chips.filter({ has: page.getByRole("img", { name: "dark.png", exact: true }) }).getByRole("button", { name: "Remove attachment", exact: true });
|
||||
await darkRemove.focus();
|
||||
await expect(darkRemove).toBeFocused();
|
||||
await page.keyboard.press("Delete");
|
||||
await expect(chips).toHaveCount(2);
|
||||
await chips.filter({ has: page.getByRole("img", { name: "notes.png", exact: true }) }).getByRole("button").click();
|
||||
await document.getByRole("button").click();
|
||||
await chips.filter({ has: page.getByRole("img", { name: "notes.png", exact: true }) }).getByRole("button", { name: "Remove attachment", exact: true }).click();
|
||||
await document.getByRole("button", { name: "Remove attachment", exact: true }).click();
|
||||
await expect(page.getByRole("textbox")).toBeFocused();
|
||||
await expect(page.getByRole("textbox")).toHaveValue("Compare these images with the report.");
|
||||
});
|
||||
@@ -91,13 +115,25 @@ for (const { width, dark, variant } of [
|
||||
|
||||
test("shows a readable error card and allows removal of a corrupt image", async ({ page }) => {
|
||||
await page.goto("/browser/fixture.html?case=composer-action");
|
||||
const input = page.getByRole("textbox");
|
||||
const draft = "Keep this draft while checking the attachment.";
|
||||
await input.fill(draft);
|
||||
const broken = Buffer.from("not a PNG image");
|
||||
await page.locator('input[type="file"]').setInputFiles({ name: "broken.png", mimeType: "image/png", buffer: broken });
|
||||
const chip = page.getByTestId("composer-chip");
|
||||
await expect(chip).toContainText("broken.png");
|
||||
await expect(chip).toContainText("File doesn't look like a real image");
|
||||
await expect(chip.getByRole("button", { name: "broken.png", exact: true })).toHaveText("PNG");
|
||||
await expect(chip.getByText("File doesn't look like a real image", { exact: true })).toBeVisible();
|
||||
await expectAttachmentDetails(page, chip, "broken.png");
|
||||
await expect(page.getByRole("button", { name: "Send message", exact: true })).toBeDisabled();
|
||||
await chip.getByRole("button", { name: "Remove attachment" }).click();
|
||||
await input.press("Enter");
|
||||
await expect(page.getByRole("status", { name: "Execution status", exact: true })).toHaveText("Idle");
|
||||
await expect(input).toHaveValue(draft);
|
||||
await expect(chip).toHaveCount(1);
|
||||
await chip.getByRole("button", { name: "Remove attachment", exact: true }).click();
|
||||
await expect(chip).toHaveCount(0);
|
||||
await expect(input).toBeFocused();
|
||||
await expect(input).toHaveValue(draft);
|
||||
await expect(page.getByRole("button", { name: "Send message", exact: true })).toBeEnabled();
|
||||
await input.fill("");
|
||||
await expect(page.getByRole("button", { name: "Voice input", exact: true })).toBeEnabled();
|
||||
await expect(page.getByRole("textbox")).toBeFocused();
|
||||
});
|
||||
@@ -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>;
|
||||
}
|
||||
@@ -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({
|
||||
|
||||
@@ -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}
|
||||
|
||||
@@ -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>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,53 @@
|
||||
export interface ImageDimensions {
|
||||
width: number;
|
||||
height: number;
|
||||
}
|
||||
|
||||
export interface ImageRow {
|
||||
start: number;
|
||||
widths: number[];
|
||||
height: number;
|
||||
}
|
||||
|
||||
export const IMAGE_GAP = 8;
|
||||
|
||||
// Extreme screenshots keep their full content inside a bounded portrait/landscape frame.
|
||||
export function imageFrameRatio(image: ImageDimensions | null): number {
|
||||
return image ? Math.max(0.5, Math.min(3, image.width / image.height)) : 1.5;
|
||||
}
|
||||
|
||||
/** Choose ordered, equal-height rows for the gallery's at most four previews. */
|
||||
export function layoutImageRows(
|
||||
images: (ImageDimensions | null)[],
|
||||
width: number,
|
||||
targetHeight: number,
|
||||
maxHeight: number,
|
||||
): ImageRow[] {
|
||||
let best: ImageRow[] = [];
|
||||
let bestScore = Infinity;
|
||||
const ratios = images.map(imageFrameRatio);
|
||||
|
||||
function visit(start: number, rows: ImageRow[], score: number) {
|
||||
if (start === images.length) {
|
||||
if (score < bestScore) { best = rows; bestScore = score; }
|
||||
return;
|
||||
}
|
||||
if (rows.length === 2) return;
|
||||
for (let end = start + 1; end <= images.length; end += 1) {
|
||||
const count = end - start;
|
||||
const rowRatios = ratios.slice(start, end);
|
||||
const ratioSum = rowRatios.reduce((sum, ratio) => sum + ratio, 0);
|
||||
const naturalHeight = Math.min(...images.slice(start, end).map((image, i) =>
|
||||
image ? Math.min(image.height, image.width / rowRatios[i]) : maxHeight));
|
||||
const height = Math.min((width - IMAGE_GAP * (count - 1)) / ratioSum, maxHeight, naturalHeight);
|
||||
const widths = rowRatios.map((ratio) => ratio * height);
|
||||
const unusedWidth = (width - ratioSum * height - IMAGE_GAP * (count - 1)) / width;
|
||||
const rowScore = count * (Math.log(height / targetHeight) ** 2 + unusedWidth ** 2) + 0.55;
|
||||
const lonelyLast = end === images.length && count === 1 && images.length > 2 ? 0.25 : 0;
|
||||
visit(end, [...rows, { start, widths, height }], score + rowScore + lonelyLast);
|
||||
}
|
||||
}
|
||||
|
||||
visit(0, [], 0);
|
||||
return best;
|
||||
}
|
||||
@@ -1,7 +1,12 @@
|
||||
import { render, screen } from "@testing-library/react";
|
||||
import { describe, expect, it } from "vitest";
|
||||
import { render, screen, within } from "@testing-library/react";
|
||||
import userEvent from "@testing-library/user-event";
|
||||
import { beforeAll, describe, expect, it } from "vitest";
|
||||
|
||||
import { AttachmentTile } from "@/components/AttachmentTile";
|
||||
import { MessageBubble } from "@/components/MessageBubble";
|
||||
import { preloadMarkdownText } from "@/components/MarkdownText";
|
||||
|
||||
beforeAll(preloadMarkdownText);
|
||||
|
||||
describe("attachment download cards", () => {
|
||||
it("keeps named download actions distinct and shows the file extension", () => {
|
||||
@@ -14,9 +19,9 @@ describe("attachment download cards", () => {
|
||||
expect(archive).toHaveAttribute("download", "猫咪图鉴完整包.zip");
|
||||
expect(archive).toHaveAttribute("href", "/api/media/signed/archive");
|
||||
expect(archive).toHaveAttribute("title", "猫咪图鉴完整包.zip");
|
||||
expect(archive).toHaveTextContent("ZIP");
|
||||
expect(archive.closest("[data-file-attachment]")).toHaveTextContent("ZIP");
|
||||
expect(archive.querySelector(".lucide-download")).toHaveAttribute("aria-hidden", "true");
|
||||
expect(screen.getByRole("link", { name: "Download source.tar.gz" })).toHaveTextContent("TAR.GZ");
|
||||
expect(screen.getByRole("link", { name: "Download source.tar.gz" }).closest("[data-file-attachment]")).toHaveTextContent("TAR.GZ");
|
||||
});
|
||||
|
||||
it("changes a pending file to a download only after its URL arrives", () => {
|
||||
@@ -26,7 +31,8 @@ describe("attachment download cards", () => {
|
||||
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");
|
||||
expect(screen.getByRole("link", { name: "Download report.pdf" })).toHaveAttribute("href", "/api/media/signed/report");
|
||||
expect(screen.getByText("PDF")).toBeVisible();
|
||||
|
||||
rerender(<AttachmentTile attachment={attachment} />);
|
||||
expect(screen.getByText("Attachment unavailable")).toBeVisible();
|
||||
@@ -40,8 +46,40 @@ describe("attachment download cards", () => {
|
||||
</>);
|
||||
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");
|
||||
expect(unnamed.closest("[data-file-attachment]")).toHaveTextContent("ZIP");
|
||||
expect(screen.getByRole("link", { name: "Download LICENSE" }).closest("[data-file-attachment]")).toHaveTextContent("File attachment");
|
||||
});
|
||||
});
|
||||
|
||||
describe("delivered file type cards", () => {
|
||||
it.each(["user", "assistant"] as const)("keeps %s file information and named downloads separate", async (role) => {
|
||||
const user = userEvent.setup();
|
||||
const { container } = render(<MessageBubble message={{ id: `files-${role}`, role, content: "Files ready", createdAt: 1,
|
||||
media: [
|
||||
{ kind: "file", name: "render-config.json", url: "/api/media/signed/first" },
|
||||
{ kind: "file", name: "another-config.json", url: "/api/media/signed/second" },
|
||||
] }} />);
|
||||
const cards = container.querySelectorAll("[data-file-attachment]");
|
||||
expect(Array.from(cards).map((card) => card.textContent)).toEqual(["JSON", "JSON"]);
|
||||
const first = within(cards[0] as HTMLElement);
|
||||
const download = first.getByRole("link", { name: "Download render-config.json" });
|
||||
expect(download).toHaveAttribute("href", "/api/media/signed/first");
|
||||
expect(download).toHaveAttribute("download", "render-config.json");
|
||||
await user.click(first.getByRole("button", { name: "render-config.json" }));
|
||||
expect(await screen.findByRole("dialog", { name: "render-config.json" })).toHaveTextContent("render-config.json");
|
||||
await user.keyboard("{Escape}");
|
||||
expect(first.getByRole("button", { name: "render-config.json" })).toHaveFocus();
|
||||
expect(within(cards[1] as HTMLElement).getByRole("link", { name: "Download another-config.json" })).toHaveAttribute("href", "/api/media/signed/second");
|
||||
});
|
||||
|
||||
it("keeps a file link inside its paragraph instead of extracting it into an attachment card", async () => {
|
||||
const { container } = render(<MessageBubble message={{ id: "inline-file", role: "assistant", createdAt: 1,
|
||||
content: "Before [notes.txt](https://example.com/notes.txt) after.",
|
||||
media: [{ kind: "file", name: "report.pdf", url: "/api/media/signed/report" }] }} />);
|
||||
const link = await screen.findByRole("link", { name: "notes.txt" });
|
||||
expect(link.closest("p")).toHaveTextContent("Before notes.txt after.");
|
||||
expect(link).toHaveAttribute("href", "https://example.com/notes.txt");
|
||||
expect(container.querySelectorAll("[data-file-attachment]")).toHaveLength(1);
|
||||
expect(screen.getByRole("link", { name: "Download report.pdf" })).toHaveAttribute("download", "report.pdf");
|
||||
});
|
||||
});
|
||||
@@ -1,4 +1,4 @@
|
||||
import { fireEvent, render, screen } from "@testing-library/react";
|
||||
import { fireEvent, render, screen, within } from "@testing-library/react";
|
||||
import { describe, expect, it, vi } from "vitest";
|
||||
|
||||
import { AttachmentTile } from "@/components/AttachmentTile";
|
||||
@@ -48,30 +48,45 @@ describe("shared file icons", () => {
|
||||
expect(svg.querySelector("text, [fill], [stroke]")).toBeNull();
|
||||
});
|
||||
|
||||
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) => {
|
||||
it.each([
|
||||
["chart.png", "PNG"],
|
||||
["index.html", "HTML"],
|
||||
["data.json", "JSON"],
|
||||
["script.py", "PY"],
|
||||
["notes.md", "MD"],
|
||||
["archive.zip", "ZIP"],
|
||||
["report.pdf", "PDF"],
|
||||
["budget.xlsx", "XLSX"],
|
||||
["slides.pptx", "PPTX"],
|
||||
["song.mp3", "MP3"],
|
||||
])(
|
||||
"shares reply and tab glyphs for %s while keeping attachment type cards and actions distinct", (path, type) => {
|
||||
const open = vi.fn();
|
||||
render(<>
|
||||
const references = render(<>
|
||||
<FileReferenceChip path={path} onOpen={open} />
|
||||
<PreviewPane tabs={[{ id: path, value: path }]} activeId={path}
|
||||
width={544} isClosing={false} onSelect={() => {}} onCloseTab={() => {}}
|
||||
onClose={() => {}} onResizeStart={() => {}}><p>Preview</p></PreviewPane>
|
||||
<AttachmentTile attachment={{ kind: "file", name: path, url: `/download/${path}` }} />
|
||||
</>);
|
||||
const reference = screen.getByRole("button", { name: path });
|
||||
const tab = screen.getByRole("tab", { name: path });
|
||||
const attachment = screen.getByRole("link", { name: `Download ${path}` });
|
||||
const attachments = render(<AttachmentTile attachment={{ kind: "file", name: path, url: `/download/${path}` }} />);
|
||||
const reference = within(references.container).getByRole("button", { name: path });
|
||||
const tab = within(references.container).getByRole("tab", { name: path });
|
||||
const information = within(attachments.container).getByRole("button", { name: path });
|
||||
const download = within(attachments.container).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-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}`);
|
||||
expect(attachment).toHaveAttribute("download", path);
|
||||
expect(within(information).getByText(type)).toBeVisible();
|
||||
expect(information.querySelector("svg")).toHaveClass("lucide-file-text");
|
||||
expect(download.querySelector("svg")).toHaveClass("lucide-download", "size-4");
|
||||
expect(download).toHaveAttribute("href", `/download/${path}`);
|
||||
expect(download).toHaveAttribute("download", path);
|
||||
fireEvent.click(reference);
|
||||
expect(open).toHaveBeenCalledWith(path);
|
||||
fireEvent.click(information);
|
||||
expect(screen.getByRole("dialog", { name: path })).toHaveTextContent(path);
|
||||
expect(open).toHaveBeenCalledTimes(1);
|
||||
},
|
||||
);
|
||||
|
||||
@@ -88,10 +103,15 @@ describe("shared file icons", () => {
|
||||
expect(open).toHaveBeenCalledWith("/repo/src/app.tsx");
|
||||
});
|
||||
|
||||
it.each(["image", "video"] as const)("retains %s identity when its attachment is unavailable", (kind) => {
|
||||
const { container } = render(<AttachmentTile attachment={{ kind, name: "Unavailable" }} />);
|
||||
expect(container.querySelector("svg")).toHaveClass(kind === "image" ? "lucide-file-image" : "lucide-file-video2");
|
||||
it.each([
|
||||
["image", "Image attachment"],
|
||||
["video", "Video attachment"],
|
||||
] as const)("retains %s identity when its attachment is unavailable", (kind, label) => {
|
||||
render(<AttachmentTile attachment={{ kind, name: "Unavailable" }} />);
|
||||
const information = screen.getByRole("button", { name: "Unavailable" });
|
||||
expect(within(information).getByText(label)).toBeVisible();
|
||||
expect(information).toHaveAccessibleDescription("Attachment unavailable");
|
||||
expect(screen.queryByRole("link")).not.toBeInTheDocument();
|
||||
expect(screen.getByText("Attachment unavailable")).toBeInTheDocument();
|
||||
expect(screen.getByText("Attachment unavailable")).toBeVisible();
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,57 @@
|
||||
import { describe, expect, it } from "vitest";
|
||||
|
||||
import { IMAGE_GAP, layoutImageRows } from "@/lib/image-gallery-layout";
|
||||
|
||||
const square = { width: 800, height: 800 };
|
||||
|
||||
describe("ordered image layout", () => {
|
||||
it("chooses two balanced rows for four square images, rather than a tiny single strip", () => {
|
||||
const rows = layoutImageRows([square, square, square, square], 360, 144, 224);
|
||||
expect(rows.map((row) => row.widths.length)).toEqual([2, 2]);
|
||||
for (const row of rows) {
|
||||
expect(row.height).toBe(176);
|
||||
expect(row.widths).toEqual([176, 176]);
|
||||
}
|
||||
});
|
||||
|
||||
it.each([360, 240])("preserves the order and native proportions of mixed images at %ipx", (width) => {
|
||||
const images = [
|
||||
{ width: 1200, height: 800 },
|
||||
{ width: 600, height: 900 },
|
||||
square,
|
||||
{ width: 1600, height: 900 },
|
||||
];
|
||||
const rows = layoutImageRows(images, width, 144, 224);
|
||||
let position = 0;
|
||||
for (const row of rows) {
|
||||
expect(row.start).toBe(position);
|
||||
expect(row.height).toBeGreaterThan(0);
|
||||
expect(row.height).toBeLessThanOrEqual(224);
|
||||
expect(row.widths.reduce((sum, item) => sum + item, IMAGE_GAP * (row.widths.length - 1))).toBeLessThanOrEqual(width + 0.001);
|
||||
for (const tileWidth of row.widths) {
|
||||
expect(tileWidth / row.height).toBeCloseTo(images[position].width / images[position].height);
|
||||
position += 1;
|
||||
}
|
||||
}
|
||||
expect(position).toBe(images.length);
|
||||
expect(rows.length).toBeLessThanOrEqual(2);
|
||||
});
|
||||
|
||||
it("fits a single portrait without stretching it into a square or exceeding the height limit", () => {
|
||||
const [row] = layoutImageRows([{ width: 600, height: 900 }], 360, 144, 320);
|
||||
expect(row.height).toBe(320);
|
||||
expect(row.widths[0]).toBeCloseTo(320 * 2 / 3);
|
||||
});
|
||||
|
||||
it("does not enlarge a small image beyond its original resolution", () => {
|
||||
const [row] = layoutImageRows([{ width: 48, height: 32 }], 360, 144, 320);
|
||||
expect(row).toEqual({ start: 0, widths: [48], height: 32 });
|
||||
});
|
||||
|
||||
it("gives extreme screenshots a bounded frame instead of a nearly invisible sliver", () => {
|
||||
const [long] = layoutImageRows([{ width: 600, height: 4800 }], 360, 144, 320);
|
||||
const [wide] = layoutImageRows([{ width: 4800, height: 600 }], 360, 144, 320);
|
||||
expect(long).toEqual({ start: 0, widths: [160], height: 320 });
|
||||
expect(wide).toEqual({ start: 0, widths: [360], height: 120 });
|
||||
});
|
||||
});
|
||||
@@ -70,13 +70,60 @@ describe("image presentation", () => {
|
||||
expect(within(screen.getByRole("dialog")).getByRole("img", { name: "0.png" })).toBeVisible();
|
||||
});
|
||||
|
||||
it("replaces a broken thumbnail with a quiet named placeholder", () => {
|
||||
it("shows an explicit failure without painting a filename across the thumbnail", () => {
|
||||
render(<ImageGallery images={[images[0]]} />);
|
||||
fireEvent.error(screen.getByRole("img"));
|
||||
expect(screen.queryByRole("img")).not.toBeInTheDocument();
|
||||
expect(screen.getByText("0.png")).toBeVisible();
|
||||
expect(screen.getByText("Attachment unavailable")).toBeVisible();
|
||||
expect(screen.getByLabelText("Attachment unavailable: 0.png")).toHaveAttribute("title", "0.png");
|
||||
expect(screen.queryByText("0.png")).not.toBeInTheDocument();
|
||||
expect(screen.queryByRole("button")).not.toBeInTheDocument();
|
||||
});
|
||||
|
||||
it("uses the loaded picture's shape for a sent user image and retains its accessible viewer action", async () => {
|
||||
const user = userEvent.setup();
|
||||
render(<MessageBubble message={{ id: "portrait", role: "user", content: "", createdAt: 1,
|
||||
images: [{ url: "/portrait.png", name: "portrait.png" }] }} />);
|
||||
const image = screen.getByRole("img", { name: "portrait.png" });
|
||||
Object.defineProperties(image, { naturalWidth: { value: 600 }, naturalHeight: { value: 900 } });
|
||||
fireEvent.load(image);
|
||||
const open = screen.getByRole("button", { name: "View image: portrait.png" });
|
||||
expect(Number.parseFloat(open.style.width)).toBeCloseTo(320 * 2 / 3);
|
||||
expect(open.style.height).toBe("320px");
|
||||
expect(screen.queryByText("portrait.png")).not.toBeInTheDocument();
|
||||
await user.click(open);
|
||||
expect(within(screen.getByRole("dialog")).getByRole("img", { name: "portrait.png" })).toBeVisible();
|
||||
});
|
||||
|
||||
it("settles a mixed gallery together after loading and preserves click order through regrouping", async () => {
|
||||
const user = userEvent.setup();
|
||||
const { container } = render(<ImageGallery images={images.slice(0, 4)} size="compact" />);
|
||||
for (const image of screen.getAllByRole("img")) {
|
||||
Object.defineProperties(image, { naturalWidth: { value: 800 }, naturalHeight: { value: 800 } });
|
||||
fireEvent.load(image);
|
||||
}
|
||||
const tiles = Array.from(container.querySelectorAll<HTMLElement>("[data-image-gallery] > button"));
|
||||
expect(tiles.map((tile) => Number.parseFloat(tile.style.top))).toEqual([0, 0, 184, 184]);
|
||||
expect(screen.getAllByRole("button").map((button) => button.getAttribute("aria-label"))).toEqual(
|
||||
[0, 1, 2, 3].map((index) => `View image: ${index}.png`));
|
||||
await user.click(screen.getByRole("button", { name: "View image: 2.png" }));
|
||||
expect(screen.getByText("3 / 4")).toBeVisible();
|
||||
expect(within(screen.getByRole("dialog")).getByRole("img", { name: "2.png" })).toBeVisible();
|
||||
});
|
||||
|
||||
it("returns focus to the same thumbnail when late image loads change the row grouping", async () => {
|
||||
const user = userEvent.setup();
|
||||
const { container } = render(<ImageGallery images={images.slice(0, 4)} size="compact" />);
|
||||
const thumbnails = container.querySelectorAll("[data-image-gallery] img");
|
||||
const opener = screen.getByRole("button", { name: "View image: 2.png" });
|
||||
await user.click(opener);
|
||||
for (const image of thumbnails) {
|
||||
Object.defineProperties(image, { naturalWidth: { value: 600 }, naturalHeight: { value: 900 } });
|
||||
fireEvent.load(image);
|
||||
}
|
||||
await user.keyboard("{Escape}");
|
||||
expect(screen.getByRole("button", { name: "View image: 2.png" })).toBe(opener);
|
||||
expect(opener).toHaveFocus();
|
||||
});
|
||||
});
|
||||
|
||||
describe("file quick look", () => {
|
||||
|
||||
@@ -294,7 +294,8 @@ describe("MarkdownTextRenderer", () => {
|
||||
it("renders markdown links with file-looking names as file attachments", () => {
|
||||
render(<MarkdownTextRenderer></MarkdownTextRenderer>);
|
||||
|
||||
expect(screen.getByRole("link", { name: "Download index.html" })).toHaveTextContent("index.html");
|
||||
expect(screen.getByRole("link", { name: "Download index.html" })).toHaveAttribute("download", "index.html");
|
||||
expect(screen.getByRole("button", { name: "index.html" })).toBeVisible();
|
||||
expect(screen.queryByRole("img", { name: "index.html" })).not.toBeInTheDocument();
|
||||
});
|
||||
|
||||
|
||||
@@ -1238,18 +1238,15 @@ describe("MessageBubble", () => {
|
||||
|
||||
const { container } = render(<MessageBubble message={message} />);
|
||||
|
||||
const image = container.querySelector("img")!;
|
||||
Object.defineProperties(image, { naturalWidth: { value: 1600 }, naturalHeight: { value: 900 } });
|
||||
fireEvent.load(image);
|
||||
const imageButton = screen.getByRole("button", { name: /view image/i });
|
||||
expect(imageButton).toHaveClass("w-[min(100%,28rem)]", "rounded-control");
|
||||
expect(imageButton).toHaveClass(
|
||||
"border",
|
||||
"border-border/60",
|
||||
"focus-visible:ring-2",
|
||||
);
|
||||
expect(imageButton).not.toHaveClass("hover:scale-[1.01]");
|
||||
expect(imageButton).not.toHaveClass("hover:ring-2");
|
||||
expect(imageButton).not.toHaveClass("hover:ring-primary/25");
|
||||
expect(imageButton).toHaveClass("rounded-control", "focus-visible:ring-2");
|
||||
expect(imageButton.style.width).toBe("448px");
|
||||
expect(imageButton.style.height).toBe("252px");
|
||||
expect(imageButton).not.toHaveAttribute("title");
|
||||
expect(container.querySelector("img")).toHaveClass("h-auto", "w-full", "object-contain");
|
||||
expect(image).toHaveClass("object-contain");
|
||||
});
|
||||
|
||||
it("renders mislabeled html assistant media as a file attachment", () => {
|
||||
@@ -1269,7 +1266,8 @@ describe("MessageBubble", () => {
|
||||
|
||||
const { container } = render(<MessageBubble message={message} />);
|
||||
|
||||
expect(screen.getByRole("link", { name: "Download index.html" })).toHaveTextContent("index.html");
|
||||
expect(screen.getByRole("link", { name: "Download index.html" })).toHaveAttribute("download", "index.html");
|
||||
expect(screen.getByRole("button", { name: "index.html" })).toBeVisible();
|
||||
expect(container.querySelector("img")).not.toBeInTheDocument();
|
||||
});
|
||||
|
||||
|
||||
@@ -4,7 +4,9 @@ import {
|
||||
render,
|
||||
screen,
|
||||
waitFor,
|
||||
within,
|
||||
} from "@testing-library/react";
|
||||
import userEvent from "@testing-library/user-event";
|
||||
import { beforeEach, describe, expect, it, vi } from "vitest";
|
||||
|
||||
import { ThreadComposer } from "@/components/thread/ThreadComposer";
|
||||
@@ -87,6 +89,7 @@ beforeEach(() => {
|
||||
|
||||
describe("ThreadComposer — attachments", () => {
|
||||
it("previews a picked image with size details on hover and includes its data url on send", async () => {
|
||||
const user = userEvent.setup();
|
||||
const file = pngFile("a.png", 100);
|
||||
encodeImage.mockResolvedValueOnce({ ...resolveReady(file), normalized: true, bytes: 50 });
|
||||
const onSend = vi.fn();
|
||||
@@ -103,7 +106,10 @@ describe("ThreadComposer — attachments", () => {
|
||||
});
|
||||
|
||||
expect(screen.getByRole("img", { name: "a.png" })).toHaveAttribute("src", expect.stringContaining("blob:"));
|
||||
expect(screen.getByTestId("composer-chip")).toHaveAttribute("title", "a.png\n100 B → 50 B (auto)");
|
||||
await user.hover(screen.getByRole("button", { name: "a.png" }));
|
||||
const details = await screen.findByRole("tooltip");
|
||||
expect(details).toHaveTextContent("a.png");
|
||||
expect(details).toHaveTextContent("100 B → 50 B (auto)");
|
||||
expect(screen.getByRole("button", { name: "Remove attachment" })).toHaveAccessibleDescription("a.png");
|
||||
|
||||
const textarea = screen.getByLabelText(/message input/i);
|
||||
@@ -118,6 +124,32 @@ describe("ThreadComposer — attachments", () => {
|
||||
expect(images[0].media.name).toBe("a.png");
|
||||
});
|
||||
|
||||
it("identifies same-type files through focus/tap details and removes only the chosen attachment", async () => {
|
||||
const user = userEvent.setup();
|
||||
const first = new File(['{"theme":"light"}'], "render-config.json", { type: "application/json" });
|
||||
const second = new File(['{"theme":"dark"}'], "another-config.json", { type: "application/json" });
|
||||
const onSend = vi.fn();
|
||||
render(<ThreadComposer onSend={onSend} />);
|
||||
const textarea = screen.getByLabelText(/message input/i);
|
||||
const input = textarea.closest("form")!.querySelector('input[type="file"]')!;
|
||||
await act(async () => fireEvent.change(input, { target: { files: [first, second] } }));
|
||||
const cards = screen.getAllByTestId("composer-chip");
|
||||
expect(cards.map((card) => card.textContent)).toEqual(["JSON", "JSON"]);
|
||||
const firstInfo = within(cards[0]).getByRole("button", { name: first.name });
|
||||
act(() => firstInfo.focus());
|
||||
expect(await screen.findByRole("tooltip")).toHaveTextContent(first.name);
|
||||
expect(screen.getByRole("tooltip")).toHaveTextContent(`${first.size} B`);
|
||||
await user.keyboard("{Escape}");
|
||||
await user.click(within(cards[1]).getByRole("button", { name: second.name }));
|
||||
expect(await screen.findByRole("dialog", { name: second.name })).toHaveTextContent(second.name);
|
||||
await user.keyboard("{Escape}");
|
||||
await user.click(within(cards[1]).getByRole("button", { name: "Remove attachment" }));
|
||||
expect(screen.getAllByTestId("composer-chip")).toHaveLength(1);
|
||||
expect(screen.getByRole("button", { name: first.name })).toBeVisible();
|
||||
fireEvent.keyDown(textarea, { key: "Enter" });
|
||||
expect(onSend.mock.calls[0][1].map((attachment: { media: { name: string } }) => attachment.media.name)).toEqual([first.name]);
|
||||
});
|
||||
|
||||
it("attaches a picked PDF and includes its data url on send", async () => {
|
||||
const file = pdfFile();
|
||||
const onSend = vi.fn();
|
||||
@@ -134,7 +166,7 @@ describe("ThreadComposer — attachments", () => {
|
||||
});
|
||||
|
||||
await waitFor(() =>
|
||||
expect(screen.getByTestId("composer-chip")).toHaveTextContent("report.pdf"),
|
||||
expect(screen.getByTestId("composer-chip")).toHaveTextContent("PDF"),
|
||||
);
|
||||
|
||||
const textarea = screen.getByLabelText(/message input/i);
|
||||
@@ -168,7 +200,7 @@ describe("ThreadComposer — attachments", () => {
|
||||
});
|
||||
|
||||
await waitFor(() =>
|
||||
expect(screen.getByTestId("composer-chip")).toHaveTextContent("report.csv"),
|
||||
expect(screen.getByRole("button", { name: "report.csv" })).toHaveAccessibleDescription(expect.stringContaining("B")),
|
||||
);
|
||||
|
||||
const textarea = screen.getByLabelText(/message input/i);
|
||||
@@ -242,8 +274,8 @@ describe("ThreadComposer — attachments", () => {
|
||||
|
||||
expect(screen.queryByRole("alert")).not.toBeInTheDocument();
|
||||
expect(screen.getAllByTestId("composer-chip")).toHaveLength(2);
|
||||
expect(screen.getByText("first.pdf")).toBeInTheDocument();
|
||||
expect(screen.getByText("second.pdf")).toBeInTheDocument();
|
||||
expect(screen.getByRole("button", { name: "first.pdf" })).toBeInTheDocument();
|
||||
expect(screen.getByRole("button", { name: "second.pdf" })).toBeInTheDocument();
|
||||
});
|
||||
|
||||
it("enforces the decoded attachment-total policy independently", async () => {
|
||||
@@ -317,7 +349,7 @@ describe("ThreadComposer — attachments", () => {
|
||||
});
|
||||
|
||||
await waitFor(() =>
|
||||
expect(screen.getByText("pasted.pdf")).toBeInTheDocument(),
|
||||
expect(screen.getByRole("button", { name: "pasted.pdf" })).toBeInTheDocument(),
|
||||
);
|
||||
|
||||
await act(async () => {
|
||||
@@ -332,7 +364,7 @@ describe("ThreadComposer — attachments", () => {
|
||||
});
|
||||
|
||||
await waitFor(() =>
|
||||
expect(screen.getByText("dropped.pdf")).toBeInTheDocument(),
|
||||
expect(screen.getByRole("button", { name: "dropped.pdf" })).toBeInTheDocument(),
|
||||
);
|
||||
expect(screen.getAllByTestId("composer-chip")).toHaveLength(2);
|
||||
expect(encodeImage).not.toHaveBeenCalled();
|
||||
@@ -421,7 +453,7 @@ describe("local attachment paths and video ingress", () => {
|
||||
fireEvent.change(input, { target: { value: "keep this " } });
|
||||
(input as HTMLTextAreaElement).setSelectionRange(10, 10);
|
||||
fireEvent.paste(input, { clipboardData: { items: [], getData: () => '"C:\\project\\my clip.mp4"' } });
|
||||
await waitFor(() => expect(screen.getByTestId("composer-chip")).toHaveTextContent("my clip.mp4"));
|
||||
await waitFor(() => expect(screen.getByRole("button", { name: "my clip.mp4" })).toBeInTheDocument());
|
||||
expect(input).toHaveValue("keep this ");
|
||||
expect(inspect).toHaveBeenCalledWith(local.path);
|
||||
fireEvent.keyDown(input, { key: "Enter" });
|
||||
@@ -568,7 +600,7 @@ describe("local attachment paths and video ingress", () => {
|
||||
render(<ThreadComposer onSend={onSend} onInspectAttachment={vi.fn().mockResolvedValue(document)} ingressLimits={ingressLimits({ maxFileBytes: 8, maxTotalBytes: 8 })} />);
|
||||
const input = screen.getByLabelText(/message input/i);
|
||||
fireEvent.paste(input, { clipboardData: { items: [], getData: () => document.path } });
|
||||
await screen.findByText(document.name);
|
||||
await screen.findByRole("button", { name: document.name });
|
||||
const picker = input.closest("form")!.querySelector('input[type="file"]')!;
|
||||
fireEvent.change(picker, { target: { files: [pdfFile("upload.pdf", 8)] } });
|
||||
await waitFor(() => expect(screen.getByRole("button", { name: /send message/i })).toBeEnabled());
|
||||
|
||||
@@ -2022,9 +2022,14 @@ describe("ThreadMessages", () => {
|
||||
});
|
||||
|
||||
render(<ThreadMessages messages={messages} isStreaming={false} />);
|
||||
expect(screen.getByText("result.csv")).toBeInTheDocument();
|
||||
const ownerRow = screen.getByText("result.csv")
|
||||
.closest<HTMLElement>("[data-thread-display-unit]")!;
|
||||
const information = screen.getByRole("button", { name: "result.csv" });
|
||||
const download = screen.getByRole("link", { name: "Download result.csv" });
|
||||
expect(information).toBeVisible();
|
||||
expect(download).toHaveAttribute("href", "/api/media/result.csv");
|
||||
expect(download).toHaveAttribute("download", "result.csv");
|
||||
expect(download.closest("[data-testid='activity-model-message'], [data-testid='agent-activity-content']")).toBeNull();
|
||||
const ownerRow = information.closest<HTMLElement>("[data-thread-display-unit]")!;
|
||||
expect(ownerRow).toContainElement(download);
|
||||
openAssistantBlockMenu(ownerRow);
|
||||
expect(screen.getByRole("button", { name: "Worked" })).toBeInTheDocument();
|
||||
});
|
||||
|
||||
@@ -593,9 +593,12 @@ describe("ThreadShell", () => {
|
||||
await waitFor(() => expect(onCreateChat).toHaveBeenCalledTimes(1));
|
||||
view.rerender(shell("created"));
|
||||
await waitFor(() => expect(screen.getByRole("textbox")).toHaveValue("keep the first draft"));
|
||||
expect(await screen.findByTestId("composer-chip")).toHaveTextContent("video.mp4");
|
||||
expect(within(await screen.findByTestId("composer-chip")).getByRole("button", { name: "video.mp4" })).toBeVisible();
|
||||
expect(screen.getByRole("alert")).toHaveTextContent("file not found");
|
||||
expect(store.get("websocket:created")?.attachments).toHaveLength(1);
|
||||
expect(store.get("websocket:created")).toMatchObject({
|
||||
text: "keep the first draft",
|
||||
attachments: [{ path: "/project/video.mp4", name: "video.mp4", kind: "video" }],
|
||||
});
|
||||
expect(store.has("new:chat")).toBe(false);
|
||||
client.sendAttachments.mockResolvedValue(undefined);
|
||||
fireEvent.click(screen.getByRole("button", { name: "Send message" }));
|
||||
|
||||
Reference in new issue
Block a user