Skip to content

Shared task board where people and AI coding agents work as teammates. Source-available, self-hostable.

Go

feat(attachments): copy full contents from text previews (#10646)

@lirose_tv9f28c70e5a88
diff --git a/e2e/attachment-preview-toolbar.spec.ts b/e2e/attachment-preview-toolbar.spec.ts
new file mode 100644
index 0000000000..6bff31e8a7
--- /dev/null
+++ b/e2e/attachment-preview-toolbar.spec.ts
@@ -0,0 +1,228 @@
+import { expect, test } from "@playwright/test";
+import { createTestApi, loginAsDefault } from "./helpers";
+
+const apiBase = process.env.NEXT_PUBLIC_API_URL || `http://localhost:${process.env.PORT || "8080"}`;
+
+for (const surface of ["standalone", "modal"] as const) {
+ for (const width of [1440, 390, 320]) {
+ test(`HTML toolbar keeps its controls reachable in ${surface} at ${width}px`, async ({ page, baseURL }, testInfo) => {
+ test.setTimeout(120000);
+ const local = (url: string) =>
+ ["localhost", "127.0.0.1", "[::1]"].includes(new URL(url).hostname);
+ test.skip(!local(baseURL!) || !local(apiBase), "Isolated local fixtures only");
+ await page.setViewportSize({ width, height: 900 });
+ const api = await createTestApi();
+ try {
+ const slug = await loginAsDefault(page);
+ const issue = await api.createIssue("HTML attachment toolbar");
+ const form = new FormData();
+ form.append("file", new Blob([
+ "<!doctype html><html><body><h1>Toolbar layout</h1><p>Switch between preview and source.</p></body></html>",
+ ], { type: "text/html" }), "toolbar-layout.html");
+ form.append("issue_id", issue.id);
+ const uploaded = await fetch(`${apiBase}/api/upload-file`, {
+ method: "POST",
+ headers: { Authorization: `Bearer ${api.getToken()}`, "X-Workspace-Slug": slug },
+ body: form,
+ });
+ expect(uploaded.status).toBe(200);
+ const attachment = await uploaded.json();
+ if (surface === "standalone") {
+ await page.goto(`/${slug}/attachments/${attachment.id}/preview`);
+ } else {
+ await api.updateIssue(issue.id, {
+ description: `!file[toolbar-layout.html](${attachment.markdown_url})`,
+ });
+ await page.goto(`/${slug}/issues/${issue.identifier}`);
+ await page.getByRole("button", { name: "Preview", exact: true }).first().click();
+ await expect(page.getByRole("dialog")).toBeVisible();
+ }
+
+ const source = page.getByRole("button", { name: "View source", exact: true });
+ const copy = page.getByRole("button", { name: "Copy contents", exact: true });
+ await expect(source).toBeVisible();
+ await expect(copy).toBeHidden();
+ const toolbar = source.locator("xpath=ancestor::header");
+ const more = toolbar.getByRole("button", { name: "More actions", exact: true });
+ const download = toolbar.getByRole("button", { name: "Download", exact: true });
+ const close = toolbar.getByRole("button", { name: "Close", exact: true });
+ const expectReachableControls = async () => {
+ const bounds = (await toolbar.boundingBox())!;
+ for (const control of [source, download, ...(surface === "modal" ? [close] : []), ...(await more.isVisible() ? [more] : []), ...(await copy.isVisible() ? [copy] : [])]) {
+ await expect(control).toBeInViewport({ ratio: 1 });
+ const box = (await control.boundingBox())!;
+ expect(box.x).toBeGreaterThanOrEqual(bounds.x);
+ expect(box.x + box.width).toBeLessThanOrEqual(bounds.x + bounds.width);
+ if (bounds.width < 768) {
+ expect(box.width).toBeGreaterThanOrEqual(44);
+ expect(box.height).toBeGreaterThanOrEqual(44);
+ }
+ }
+ };
+ await expectReachableControls();
+ if (width === 1440) {
+ await expect(more).toBeHidden();
+ // The preview's container, rather than the browser window, owns folding.
+ await toolbar.evaluate((element) => { element.style.width = "390px"; });
+ await expect(more).toBeVisible();
+ await expectReachableControls();
+ await toolbar.evaluate((element) => { element.style.width = ""; });
+ await expect(more).toBeHidden();
+ } else {
+ await more.focus();
+ await page.keyboard.press("ArrowDown");
+ const menu = page.getByRole("menu");
+ await expect(menu).toBeVisible();
+ await expect(menu.getByRole("menuitemradio", { name: "Fit", exact: true })).toHaveAttribute("aria-checked", "true");
+ await expect(menu.getByRole("menuitemcheckbox", { name: "Wrap lines", exact: true })).toBeDisabled();
+ await expect(menu.getByRole("menuitemradio", { name: "Fit", exact: true })).toBeFocused();
+ for (let step = 0; step < 3; step++) await page.keyboard.press("ArrowDown");
+ await expect(menu.getByRole("menuitemradio", { name: "Phone", exact: true })).toBeFocused();
+ await page.keyboard.press("Enter");
+ await expect(menu).toBeHidden();
+ await expect(more).toBeFocused();
+ if (surface === "modal") {
+ await page.keyboard.press("Tab");
+ await expect(close).toBeFocused();
+ await page.keyboard.press("Shift+Tab");
+ await expect(more).toBeFocused();
+ }
+ await more.click();
+ await expect(menu.getByRole("menuitemradio", { name: "Phone", exact: true })).toHaveAttribute("aria-checked", "true");
+ await page.keyboard.press("Escape");
+ await expect(menu).toBeHidden();
+ await expect(more).toBeFocused();
+ if (surface === "modal") await expect(page.getByRole("dialog")).toBeVisible();
+ }
+ const before = (await source.boundingBox())!;
+ const center = { x: before.x + before.width / 2, y: before.y + before.height / 2 };
+ const previewShot = testInfo.outputPath("preview.png");
+ await page.screenshot({ path: previewShot, animations: "disabled" });
+ await testInfo.attach("preview", { path: previewShot, contentType: "image/png" });
+ await page.mouse.click(center.x, center.y);
+ await expect(source).toHaveAttribute("aria-pressed", "true");
+ await expect(copy).toBeVisible();
+ await expect(copy).toBeEnabled();
+ await expectReachableControls();
+ const sourceShot = testInfo.outputPath("source.png");
+ await page.screenshot({ path: sourceShot, animations: "disabled" });
+ await testInfo.attach("source", { path: sourceShot, contentType: "image/png" });
+ expect(await source.boundingBox()).toEqual(before);
+
+ if (width < 768) {
+ await more.click();
+ const menu = page.getByRole("menu");
+ await expect(menu.getByRole("menuitemradio", { name: "Phone", exact: true })).toBeDisabled();
+ await expect(menu.getByRole("menuitem", { name: "Reload", exact: true })).toBeDisabled();
+ const wrap = menu.getByRole("menuitemcheckbox", { name: "Wrap lines", exact: true });
+ await expect(wrap).toBeEnabled();
+ await expect(wrap).toHaveAttribute("aria-checked", "false");
+ await wrap.click();
+ await expect(wrap).toHaveAttribute("aria-checked", "true");
+ if (surface === "modal" && width === 390) {
+ const menuShot = testInfo.outputPath("menu.png");
+ await page.screenshot({ path: menuShot, animations: "disabled" });
+ await testInfo.attach("menu", { path: menuShot, contentType: "image/png" });
+ }
+ await page.keyboard.press("Escape");
+ await expect(menu).toBeHidden();
+ await expect(more).toBeFocused();
+ if (surface === "modal") await expect(page.getByRole("dialog")).toBeVisible();
+ }
+
+ const [downloaded] = await Promise.all([
+ page.waitForEvent("download"),
+ download.click(),
+ ]);
+ expect(downloaded.suggestedFilename()).toBe("toolbar-layout.html");
+
+ await page.mouse.click(center.x, center.y);
+ await expect(source).toHaveAttribute("aria-pressed", "false");
+ await expect(copy).toBeHidden();
+ expect(await source.boundingBox()).toEqual(before);
+ await expectReachableControls();
+ if (surface === "modal") {
+ await close.click();
+ await expect(page.getByRole("dialog")).toBeHidden();
+ }
+ } finally {
+ await api.cleanup();
+ }
+ });
+ }
+}
+
+for (const kind of ["structured", "image"] as const) {
+ test(`compact overflow retains ${kind} controls`, async ({ page, baseURL }) => {
+ test.setTimeout(120000);
+ const local = (url: string) =>
+ ["localhost", "127.0.0.1", "[::1]"].includes(new URL(url).hostname);
+ test.skip(!local(baseURL!) || !local(apiBase), "Isolated local fixtures only");
+ await page.setViewportSize({ width: 320, height: 900 });
+ const api = await createTestApi();
+ try {
+ const slug = await loginAsDefault(page);
+ const issue = await api.createIssue(`Compact ${kind} toolbar`);
+ const form = new FormData();
+ const structured = kind === "structured";
+ form.append("file", new Blob([
+ structured
+ ? '{"name":"toolbar","enabled":true}'
+ : '<svg xmlns="http://www.w3.org/2000/svg" width="800" height="600"><rect width="800" height="600" fill="silver"/></svg>',
+ ], { type: structured ? "application/json" : "image/svg+xml" }), structured ? "toolbar.json" : "toolbar.svg");
+ form.append("issue_id", issue.id);
+ const uploaded = await fetch(`${apiBase}/api/upload-file`, {
+ method: "POST",
+ headers: { Authorization: `Bearer ${api.getToken()}`, "X-Workspace-Slug": slug },
+ body: form,
+ });
+ expect(uploaded.status).toBe(200);
+ const attachment = await uploaded.json();
+ await page.goto(`/${slug}/attachments/${attachment.id}/preview`);
+ if (structured) {
+ await expect(page.getByRole("button", { name: "Copy contents", exact: true })).toBeEnabled();
+ } else {
+ const image = page.getByRole("img", { name: "toolbar.svg", exact: true });
+ await expect.poll(() => image.evaluate((element: HTMLImageElement) => element.naturalWidth)).toBe(800);
+ }
+ const more = page.getByRole("button", { name: "More actions", exact: true });
+ await expect(more).toBeInViewport({ ratio: 1 });
+ await more.focus();
+ await page.keyboard.press("ArrowDown");
+ const menu = page.getByRole("menu");
+ if (structured) {
+ await expect(menu.getByRole("menuitemradio", { name: "Tree", exact: true })).toHaveAttribute("aria-checked", "true");
+ await expect(menu.getByRole("menuitemcheckbox", { name: "Wrap lines", exact: true })).toBeDisabled();
+ await page.keyboard.press("ArrowDown");
+ await expect(menu.getByRole("menuitemradio", { name: "Raw", exact: true })).toBeFocused();
+ await page.keyboard.press("Enter");
+ await expect(menu).toBeHidden();
+ await expect(more).toBeFocused();
+ await expect(page.locator("pre")).toContainText('{"name":"toolbar","enabled":true}');
+ await more.click();
+ await expect(menu.getByRole("menuitemradio", { name: "Raw", exact: true })).toHaveAttribute("aria-checked", "true");
+ const wrap = menu.getByRole("menuitemcheckbox", { name: "Wrap lines", exact: true });
+ await expect(wrap).toBeEnabled();
+ await wrap.click();
+ await expect(wrap).toHaveAttribute("aria-checked", "true");
+ } else {
+ await menu.getByRole("menuitem", { name: "Actual size", exact: true }).click();
+ await expect(menu).toBeHidden();
+ await expect(more).toBeFocused();
+ await more.click();
+ await expect(menu.getByText("100%", { exact: true })).toBeVisible();
+ await menu.getByRole("menuitem", { name: "Zoom out", exact: true }).click();
+ await expect(menu).toBeHidden();
+ await expect(more).toBeFocused();
+ await more.click();
+ await expect(menu.getByText("100%", { exact: true })).toHaveCount(0);
+ await expect(menu.getByRole("menuitem", { name: "Fit to view", exact: true })).toBeEnabled();
+ }
+ await page.keyboard.press("Escape");
+ await expect(menu).toBeHidden();
+ await expect(more).toBeFocused();
+ } finally {
+ await api.cleanup();
+ }
+ });
+}
diff --git a/packages/views/editor/attachment-preview-modal.test.tsx b/packages/views/editor/attachment-preview-modal.test.tsx
index b662f24486..2289a68ee0 100644
--- a/packages/views/editor/attachment-preview-modal.test.tsx
+++ b/packages/views/editor/attachment-preview-modal.test.tsx
@@ -5,12 +5,13 @@ import { useState, type ReactElement } from "react";
import type { Attachment } from "@multica/core/types";
import { ApiError } from "@multica/core/api/client";
-const { openExternalMock, isDesktopShellMock, copyImageMock, toastMock } =
+const { openExternalMock, isDesktopShellMock, copyImageMock, copyTextMock, toastMock } =
vi.hoisted(() => ({
openExternalMock: vi.fn(),
// Web by default; the copy-image tests flip it to the desktop shell.
isDesktopShellMock: vi.fn(() => false),
copyImageMock: vi.fn(async (_url: string) => true),
+ copyTextMock: vi.fn(async (_text: string) => true),
toastMock: { success: vi.fn(), error: vi.fn() },
}));
@@ -24,6 +25,7 @@ vi.mock("../platform/local-directory", () => ({
vi.mock("@multica/ui/lib/clipboard", () => ({
copyImage: copyImageMock,
+ copyText: copyTextMock,
}));
vi.mock("sonner", () => ({ toast: toastMock }));
@@ -145,6 +147,10 @@ vi.mock("../i18n", () => ({
preview_unsupported: "This file type can't be previewed.",
close: "Close",
download_failed: "",
+ copy_contents: "Copy contents",
+ contents_copied: "Contents copied",
+ copy_failed: "Couldn't copy contents",
+ more_actions: "More actions",
open_in_new_tab: "Open in new tab",
wrap_lines: "Wrap lines",
viewport: "Viewport width",
@@ -234,6 +240,7 @@ beforeEach(() => {
slugState.value = "acme";
isDesktopShellMock.mockReturnValue(false);
copyImageMock.mockResolvedValue(true);
+ copyTextMock.mockResolvedValue(true);
// Default to web's same-origin empty base so existing absolute-URL tests
// remain unaffected by the relative-URL resolution added in normalize().
getBaseUrlMock.mockReturnValue("");
@@ -857,6 +864,76 @@ describe("AttachmentPreviewModal — controls", () => {
});
});
+describe("AttachmentPreviewModal — copy contents", () => {
+ it.each([
+ ["example.php", "text/plain", "<?php\r\n// 示例\r\necho 'Hello';\r\n"],
+ ["README.md", "text/markdown", "# Heading\n\n**Keep the source**\n"],
+ ["config.json", "application/json", '{ "enabled": true, "items": [1, 2] }\n'],
+ ["report.csv", "text/csv", 'name,value\n"Example",42\n'],
+ ])("copies the complete original %s body without line numbers or formatting", async (filename, contentType, text) => {
+ getAttachmentTextContentMock.mockResolvedValueOnce({ text, originalContentType: contentType });
+ const attachment = makeAttachment({ filename, content_type: contentType });
+ render(<AttachmentPreviewModal source={{ kind: "full", attachment }} open onClose={() => {}} />);
+ const button = screen.getByRole("button", { name: "Copy contents" });
+ await waitFor(() => expect(button).toBeEnabled());
+ fireEvent.click(button);
+ expect(copyTextMock).toHaveBeenCalledWith(text);
+ expect(getAttachmentTextContentMock).toHaveBeenCalledTimes(1);
+ await waitFor(() => expect(toastMock.success).toHaveBeenCalledWith("Contents copied"));
+ });
+
+ it("uses the same copy action in the standalone preview", async () => {
+ getAttachmentTextContentMock.mockResolvedValueOnce({ text: "complete file\n", originalContentType: "text/plain" });
+ render(<AttachmentPreviewStandalone attachment={makeAttachment({ filename: "example.txt", content_type: "text/plain" })} />);
+ const button = screen.getByRole("button", { name: "Copy contents" });
+ await waitFor(() => expect(button).toBeEnabled());
+ fireEvent.click(button);
+ expect(copyTextMock).toHaveBeenCalledWith("complete file\n");
+ });
+
+ it("keeps copy disabled while loading and after a text fetch failure", async () => {
+ let reject!: (reason: Error) => void;
+ getAttachmentTextContentMock.mockReturnValueOnce(new Promise((_, fail) => { reject = fail; }));
+ render(<AttachmentPreviewModal source={{ kind: "full", attachment: makeAttachment({ filename: "example.txt", content_type: "text/plain" }) }} open onClose={() => {}} />);
+ expect(screen.getByRole("button", { name: "Copy contents" })).toBeDisabled();
+ await act(async () => reject(new Error("unavailable")));
+ expect(await screen.findByText("Couldn't load preview")).toBeInTheDocument();
+ expect(screen.getByRole("button", { name: "Copy contents" })).toBeDisabled();
+ expect(copyTextMock).not.toHaveBeenCalled();
+ });
+
+ it("reports clipboard failure without claiming success", async () => {
+ copyTextMock.mockResolvedValueOnce(false);
+ getAttachmentTextContentMock.mockResolvedValueOnce({ text: "example", originalContentType: "text/plain" });
+ render(<AttachmentPreviewModal source={{ kind: "full", attachment: makeAttachment({ filename: "example.txt", content_type: "text/plain" }) }} open onClose={() => {}} />);
+ const button = screen.getByRole("button", { name: "Copy contents" });
+ await waitFor(() => expect(button).toBeEnabled());
+ fireEvent.click(button);
+ await waitFor(() => expect(toastMock.error).toHaveBeenCalledWith("Couldn't copy contents"));
+ expect(toastMock.success).not.toHaveBeenCalled();
+ });
+
+ it("offers HTML copying only in source view", async () => {
+ const text = "<!doctype html>\n<p>Example</p>\n";
+ getAttachmentTextContentMock.mockResolvedValueOnce({ text, originalContentType: "text/html" });
+ render(<AttachmentPreviewModal source={{ kind: "full", attachment: makeAttachment({ filename: "example.html", content_type: "text/html" }) }} open onClose={() => {}} />);
+ expect(screen.queryByRole("button", { name: "Copy contents" })).toBeNull();
+ fireEvent.click(screen.getByRole("button", { name: "View source" }));
+ const button = await screen.findByRole("button", { name: "Copy contents" });
+ await waitFor(() => expect(button).toBeEnabled());
+ fireEvent.click(button);
+ expect(copyTextMock).toHaveBeenCalledWith(text);
+ });
+
+ it.each([
+ ["example.png", "image/png"],
+ ["example.pdf", "application/pdf"],
+ ])("does not offer text copying for %s", (filename, contentType) => {
+ render(<AttachmentPreviewModal source={{ kind: "full", attachment: makeAttachment({ filename, content_type: contentType }) }} open onClose={() => {}} />);
+ expect(screen.queryByRole("button", { name: "Copy contents" })).toBeNull();
+ });
+});
+
describe("AttachmentPreviewModal — copy image (MUL-7759)", () => {
const image = () =>
makeAttachment({
diff --git a/packages/views/editor/attachment-preview-modal.tsx b/packages/views/editor/attachment-preview-modal.tsx
index 19bd3192f7..76a5d22ca7 100644
--- a/packages/views/editor/attachment-preview-modal.tsx
+++ b/packages/views/editor/attachment-preview-modal.tsx
@@ -33,6 +33,7 @@ import {
Code,
Copy,
Download,
+ Ellipsis,
ExternalLink,
File,
FileAudio,
@@ -67,7 +68,19 @@ import { paths, useWorkspaceSlug } from "@multica/core/paths";
import { createShortcutChord } from "@multica/core/shortcuts";
import { cn } from "@multica/ui/lib/utils";
import { TooltipHint } from "@multica/ui/components/common/tooltip-hint";
-import { copyImage } from "@multica/ui/lib/clipboard";
+import {
+ DropdownMenu,
+ DropdownMenuCheckboxItem,
+ DropdownMenuContent,
+ DropdownMenuGroup,
+ DropdownMenuItem,
+ DropdownMenuLabel,
+ DropdownMenuRadioGroup,
+ DropdownMenuRadioItem,
+ DropdownMenuSeparator,
+ DropdownMenuTrigger,
+} from "@multica/ui/components/ui/dropdown-menu";
+import { copyImage, copyText } from "@multica/ui/lib/clipboard";
import { resolvePublicFileUrl } from "@multica/core/workspace/avatar-url";
import {
UI_EASE_OUT,
@@ -827,6 +840,17 @@ function PreviewPanel({
// headers), and there the browser's own context menu has Copy image. Copies
// the frame on screen, which during a sequence swap is still the last one.
const canCopyImage = kind === "image" && isDesktopShell();
+ const canCopyText =
+ kind !== null && TEXT_BACKED_KINDS.has(kind) && (kind !== "html" || htmlSource);
+ const copyContent = useAttachmentHtmlText(canCopyText ? state.attachmentId : null);
+ const handleCopyText = async () => {
+ if (!copyContent.data || copyContent.isError) return;
+ if (await copyText(copyContent.data.text)) {
+ toast.success(t(($) => $.attachment.contents_copied));
+ } else {
+ toast.error(t(($) => $.attachment.copy_failed));
+ }
+ };
const handleCopyImage = async () => {
if (await copyImage(mediaUrl)) {
toast.success(t(($) => $.image.image_copied));
@@ -881,6 +905,7 @@ function PreviewPanel({
const wrapButton = (enabled: boolean) => (
<ChromeButton
+ className="hidden @3xl:flex"
label={t(($) => $.attachment.wrap_lines)}
pressed={enabled && wrap}
disabled={!enabled}
@@ -895,6 +920,17 @@ function PreviewPanel({
tablet: t(($) => $.attachment.viewport_tablet),
phone: t(($) => $.attachment.viewport_phone),
};
+ const overflowTriggerRef = useRef<HTMLButtonElement>(null);
+ const restoreOverflowFocus = useRef(false);
+ const overflowActionMovesFocus = useRef(false);
+ const navigateFromOverflow = (navigate: () => void) => {
+ overflowActionMovesFocus.current = true;
+ navigate();
+ };
+ const showZoomControls = kind === "image" && !!(natural || sequence);
+ const hasViewControls = showZoomControls || kind === "html" || kind === "structured" || kind === "text";
+ const hasOverflowActions = hasViewControls || !!(locate || copyLink || onOpenInNewTab || onOpenOverview || info);
+ const canWrap = kind === "text" || (kind === "html" && htmlSource) || (kind === "structured" && structuredView === "raw");
return (
<>
@@ -903,10 +939,10 @@ function PreviewPanel({
style={surface === "viewer" ? DRAG : undefined}
>
<div className="flex min-w-0 items-center gap-2.5">
- <span className="flex size-8 shrink-0 items-center justify-center rounded-md bg-secondary text-muted-foreground">
+ <span className="hidden size-8 shrink-0 items-center justify-center rounded-md bg-secondary text-muted-foreground @3xl:flex">
<KindIcon className="size-4" />
</span>
- <div className="min-w-0">
+ <div className="min-w-0 flex-1">
<div className="flex min-w-0 items-center gap-2" style={titleAccessory ? NO_DRAG : undefined}>
{kind === "html" && !htmlSource ? (
<HtmlPreviewAddress
@@ -937,9 +973,9 @@ function PreviewPanel({
(disabled while un-measured) instead: `natural` passes through
null on every swap, and controls that vanish and reappear shift
the buttons to their right on every navigation. */}
- {kind === "image" && (natural || sequence) && (
+ {showZoomControls && (
<>
- <ZoomControls canvas={canvas} disabled={!natural} />
+ <ZoomControls className="hidden @3xl:flex" canvas={canvas} disabled={!natural} />
<ChromeDivider />
</>
)}
@@ -948,6 +984,7 @@ function PreviewPanel({
{kind === "html" && (
<>
<ChromeButton
+ className="hidden @3xl:flex"
label={t(($) => $.attachment.reload)}
disabled={htmlSource}
onClick={htmlLocation.reload}
@@ -955,6 +992,7 @@ function PreviewPanel({
<RotateCw className="size-4" />
</ChromeButton>
<ChromeSegmented
+ className="hidden @3xl:flex"
label={t(($) => $.attachment.viewport)}
value={htmlViewport}
disabled={htmlSource}
@@ -979,6 +1017,7 @@ function PreviewPanel({
{kind === "structured" && (
<>
<ChromeSegmented
+ className="hidden @3xl:flex"
label={t(($) => $.attachment.view_mode)}
value={structuredView}
disabled={!treeAvailable}
@@ -1007,17 +1046,32 @@ function PreviewPanel({
</>
)}
{locate && (
- <ChromeButton label={locate.label} onClick={locate.onSelect}>
+ <ChromeButton className="hidden @3xl:flex" label={locate.label} onClick={locate.onSelect}>
<MessageSquareText className="size-4" />
</ChromeButton>
)}
+ {/* Reserve the HTML copy slot so switching source never moves its toggle. */}
+ {(canCopyText || kind === "html") && (
+ <div className="size-11 shrink-0 @3xl:size-8">
+ {canCopyText && (
+ <ChromeButton
+ label={t(($) => $.attachment.copy_contents)}
+ disabled={!copyContent.data || copyContent.isError}
+ onClick={() => void handleCopyText()}
+ >
+ <Copy className="size-4" />
+ </ChromeButton>
+ )}
+ </div>
+ )}
{copyLink && (
- <ChromeButton label={copyLink.label} onClick={copyLink.onSelect}>
+ <ChromeButton className="hidden @3xl:flex" label={copyLink.label} onClick={copyLink.onSelect}>
<Link2 className="size-4" />
</ChromeButton>
)}
{onOpenInNewTab && (
<ChromeButton
+ className="hidden @3xl:flex"
label={t(($) => $.attachment.open_in_new_tab)}
onClick={onOpenInNewTab}
>
@@ -1045,9 +1099,142 @@ function PreviewPanel({
<Download className="size-4" />
)}
</ChromeButton>
+ {hasOverflowActions && (
+ <div className="@3xl:hidden">
+ <DropdownMenu
+ onOpenChange={(open, details) => {
+ if (open) {
+ restoreOverflowFocus.current = false;
+ overflowActionMovesFocus.current = false;
+ } else if (details.reason !== "trigger-hover") {
+ // Hover dismissal can follow item selection or Escape during exit.
+ restoreOverflowFocus.current = details.reason === "escape-key" ||
+ (details.reason === "item-press" && !overflowActionMovesFocus.current);
+ }
+ }}
+ onOpenChangeComplete={(open) => {
+ if (!open && restoreOverflowFocus.current) {
+ restoreOverflowFocus.current = false;
+ overflowTriggerRef.current?.focus({ preventScroll: true });
+ }
+ }}
+ >
+ <DropdownMenuTrigger
+ ref={overflowTriggerRef}
+ render={
+ <button
+ type="button"
+ aria-label={t(($) => $.attachment.more_actions)}
+ className="flex size-11 shrink-0 items-center justify-center rounded-md text-muted-foreground transition-colors hover:bg-secondary hover:text-foreground"
+ >
+ <Ellipsis className="size-4" />
+ </button>
+ }
+ />
+ <DropdownMenuContent
+ align="end"
+ className="dark w-72 max-w-[calc(100vw-1rem)] [&_[role^=menuitem]]:min-h-11"
+ >
+ {kind === "html" && (
+ <DropdownMenuGroup>
+ <DropdownMenuLabel>{t(($) => $.attachment.viewport)}</DropdownMenuLabel>
+ <DropdownMenuRadioGroup
+ className="grid grid-cols-2 gap-0.5"
+ value={htmlViewport}
+ onValueChange={(value) => setHtmlViewport(value as HtmlViewport)}
+ >
+ {HTML_VIEWPORTS.map((viewport) => (
+ <DropdownMenuRadioItem key={viewport} value={viewport} disabled={htmlSource}>
+ {viewportLabels[viewport]}
+ </DropdownMenuRadioItem>
+ ))}
+ </DropdownMenuRadioGroup>
+ <DropdownMenuItem onClick={htmlLocation.reload} disabled={htmlSource}>
+ <RotateCw className="size-4" />
+ {t(($) => $.attachment.reload)}
+ </DropdownMenuItem>
+ </DropdownMenuGroup>
+ )}
+ {kind === "structured" && (
+ <DropdownMenuGroup>
+ <DropdownMenuLabel>{t(($) => $.attachment.view_mode)}</DropdownMenuLabel>
+ <DropdownMenuRadioGroup
+ value={structuredView}
+ onValueChange={(value) => setStructuredChoice(value as StructuredView)}
+ >
+ <DropdownMenuRadioItem value="tree" disabled={!treeAvailable}>
+ <ListTree className="size-4" />
+ {t(($) => $.attachment.view_tree)}
+ </DropdownMenuRadioItem>
+ <DropdownMenuRadioItem value="raw" disabled={!treeAvailable}>
+ <Code className="size-4" />
+ {t(($) => $.attachment.view_raw)}
+ </DropdownMenuRadioItem>
+ </DropdownMenuRadioGroup>
+ </DropdownMenuGroup>
+ )}
+ {(kind === "html" || kind === "structured" || kind === "text") && (
+ <DropdownMenuCheckboxItem checked={canWrap && wrap} disabled={!canWrap} closeOnClick={false} onCheckedChange={setWrapChoice}>
+ <WrapText className="size-4" />
+ {t(($) => $.attachment.wrap_lines)}
+ </DropdownMenuCheckboxItem>
+ )}
+ {showZoomControls && (
+ <DropdownMenuGroup>
+ <DropdownMenuLabel>{canvas.zoomPercent}%</DropdownMenuLabel>
+ <DropdownMenuItem onClick={canvas.zoomOut} disabled={!natural || !canvas.canZoomOut}>
+ {t(($) => $.canvas.zoom_out)}
+ </DropdownMenuItem>
+ <DropdownMenuItem onClick={canvas.zoomIn} disabled={!natural || !canvas.canZoomIn}>
+ {t(($) => $.canvas.zoom_in)}
+ </DropdownMenuItem>
+ <DropdownMenuItem onClick={canvas.fit} disabled={!natural}>
+ {t(($) => $.canvas.zoom_fit)}
+ </DropdownMenuItem>
+ <DropdownMenuItem onClick={canvas.zoomToActualSize} disabled={!natural}>
+ {t(($) => $.canvas.zoom_actual)}
+ </DropdownMenuItem>
+ </DropdownMenuGroup>
+ )}
+ {hasViewControls && (locate || copyLink || onOpenInNewTab || onOpenOverview || info) && <DropdownMenuSeparator />}
+ {locate && (
+ <DropdownMenuItem onClick={() => navigateFromOverflow(locate.onSelect)}>
+ <MessageSquareText className="size-4" />
+ {locate.label}
+ </DropdownMenuItem>
+ )}
+ {copyLink && (
+ <DropdownMenuItem onClick={copyLink.onSelect}>
+ <Link2 className="size-4" />
+ {copyLink.label}
+ </DropdownMenuItem>
+ )}
+ {onOpenInNewTab && (
+ <DropdownMenuItem onClick={() => navigateFromOverflow(onOpenInNewTab)}>
+ <ExternalLink className="size-4" />
+ {t(($) => $.attachment.open_in_new_tab)}
+ </DropdownMenuItem>
+ )}
+ {onOpenOverview && (
+ <DropdownMenuItem onClick={() => navigateFromOverflow(onOpenOverview)}>
+ <LayoutGrid className="size-4" />
+ {t(($) => $.attachment.overview)}
+ </DropdownMenuItem>
+ )}
+ {info && (
+ <DropdownMenuCheckboxItem checked={info.open} closeOnClick onCheckedChange={info.onToggle}>
+ <PanelRight className="size-4" />
+ {t(($) => $.attachment.info)}
+ </DropdownMenuCheckboxItem>
+ )}
+ </DropdownMenuContent>
+ </DropdownMenu>
+ </div>
+ )}
{(onOpenOverview || info) && <ChromeDivider />}
{onOpenOverview && (
<ChromeButton
+ className="hidden @3xl:flex"
label={t(($) => $.attachment.overview)}
shortcut="G"
onClick={onOpenOverview}
@@ -1057,6 +1244,7 @@ function PreviewPanel({
)}
{info && (
<ChromeButton
+ className="hidden @3xl:flex"
label={t(($) => $.attachment.info)}
shortcut="I"
pressed={info.open}
@@ -1141,6 +1329,7 @@ function PreviewPanel({
// Top-bar icon button. Sits inside the `dark` header, so the semantic tokens
// resolve to the dark set whatever the app theme is.
function ChromeButton({
+ className,
label,
shortcut,
pressed,
@@ -1149,6 +1338,7 @@ function ChromeButton({
onClick,
children,
}: {
+ className?: string;
label: string;
/** Single-key shortcut, shown in the tooltip and announced to AT. */
shortcut?: string;
@@ -1172,8 +1362,9 @@ function ChromeButton({
<button
type="button"
className={cn(
- "flex size-8 items-center justify-center rounded-md transition-colors enabled:hover:bg-secondary enabled:hover:text-foreground disabled:opacity-40",
+ "flex size-11 shrink-0 items-center justify-center rounded-md transition-colors enabled:hover:bg-secondary enabled:hover:text-foreground disabled:opacity-40 @3xl:size-8",
pressed ? "bg-secondary text-foreground" : "text-muted-foreground",
+ className,
)}
aria-label={label}
aria-keyshortcuts={shortcut}
@@ -1192,12 +1383,14 @@ function ChromeButton({
// pressed look as the toggle buttons beside it. Labels show once the bar has
// room for them; below that the icons carry the choice, named by tooltip.
function ChromeSegmented<T extends string>({
+ className,
label,
value,
options,
disabled,
onChange,
}: {
+ className?: string;
label: string;
value: T;
options: ReadonlyArray<{ value: T; label: string; icon: IconComponent }>;
@@ -1205,7 +1398,7 @@ function ChromeSegmented<T extends string>({
onChange: (value: T) => void;
}) {
return (
- <div role="group" aria-label={label} className="flex items-center gap-0.5">
+ <div role="group" aria-label={label} className={cn("flex items-center gap-0.5", className)}>
{options.map((option) => {
const pressed = option.value === value;
const Icon = option.icon;
@@ -1235,7 +1428,7 @@ function ChromeSegmented<T extends string>({
}
function ChromeDivider() {
- return <span className="mx-1.5 h-4 w-px bg-input" aria-hidden />;
+ return <span className="mx-1.5 hidden h-4 w-px bg-input @3xl:block" aria-hidden />;
}
// Prev / next with the position between them, centered under the stage. The
diff --git a/packages/views/locales/en/editor.json b/packages/views/locales/en/editor.json
index 805b97465a..f2013ad868 100644
--- a/packages/views/locales/en/editor.json
+++ b/packages/views/locales/en/editor.json
@@ -56,6 +56,10 @@
"install_theme": "Install theme",
"install_theme_failed": "Couldn't read the attachment. Try again in a moment.",
"download_failed": "Couldn't fetch a download link. Try again in a moment.",
+ "copy_contents": "Copy contents",
+ "contents_copied": "Contents copied",
+ "copy_failed": "Couldn't copy contents",
+ "more_actions": "More actions",
"preview": "Preview",
"preview_loading": "Loading preview…",
"preview_failed": "Couldn't load preview",
diff --git a/packages/views/locales/es/editor.json b/packages/views/locales/es/editor.json
index c5f823a747..1b62948d70 100644
--- a/packages/views/locales/es/editor.json
+++ b/packages/views/locales/es/editor.json
@@ -56,6 +56,10 @@
"install_theme": "Instalar tema",
"install_theme_failed": "No se pudo leer el adjunto. Inténtalo de nuevo en un momento.",
"download_failed": "No se ha podido obtener un enlace de descarga. Inténtalo de nuevo en un momento.",
+ "copy_contents": "Copiar contenido",
+ "contents_copied": "Contenido copiado",
+ "copy_failed": "No se pudo copiar el contenido",
+ "more_actions": "Más acciones",
"preview": "Vista previa",
"preview_loading": "Cargando vista previa…",
"preview_failed": "No se ha podido cargar la vista previa",
diff --git a/packages/views/locales/fr/editor.json b/packages/views/locales/fr/editor.json
index 34f328abac..dca8549aca 100644
--- a/packages/views/locales/fr/editor.json
+++ b/packages/views/locales/fr/editor.json
@@ -56,6 +56,10 @@
"install_theme": "Installer le thème",
"install_theme_failed": "Impossible de lire la pièce jointe. Réessayez dans un instant.",
"download_failed": "Impossible d'obtenir un lien de téléchargement. Réessayez dans un instant.",
+ "copy_contents": "Copier le contenu",
+ "contents_copied": "Contenu copié",
+ "copy_failed": "Impossible de copier le contenu",
+ "more_actions": "Plus d’actions",
"preview": "Aperçu",
"preview_loading": "Chargement de l'aperçu…",
"preview_failed": "Impossible de charger l'aperçu",
diff --git a/packages/views/locales/ja/editor.json b/packages/views/locales/ja/editor.json
index def05b53e2..86e6955b47 100644
--- a/packages/views/locales/ja/editor.json
+++ b/packages/views/locales/ja/editor.json
@@ -56,6 +56,10 @@
"install_theme": "テーマをインストール",
"install_theme_failed": "添付ファイルを読み込めませんでした。しばらくしてからもう一度お試しください。",
"download_failed": "ダウンロードリンクを取得できませんでした。しばらくしてからもう一度お試しください。",
+ "copy_contents": "内容をコピー",
+ "contents_copied": "内容をコピーしました",
+ "copy_failed": "内容をコピーできませんでした",
+ "more_actions": "その他の操作",
"preview": "プレビュー",
"preview_loading": "プレビューを読み込み中…",
"preview_failed": "プレビューを読み込めませんでした",
diff --git a/packages/views/locales/ko/editor.json b/packages/views/locales/ko/editor.json
index 4281e706bb..f115c3df84 100644
--- a/packages/views/locales/ko/editor.json
+++ b/packages/views/locales/ko/editor.json
@@ -56,6 +56,10 @@
"install_theme": "테마 설치",
"install_theme_failed": "첨부 파일을 읽을 수 없습니다. 잠시 후 다시 시도하세요.",
"download_failed": "다운로드 링크를 가져오지 못했습니다. 잠시 후 다시 시도하세요.",
+ "copy_contents": "내용 복사",
+ "contents_copied": "내용을 복사했습니다",
+ "copy_failed": "내용을 복사하지 못했습니다",
+ "more_actions": "추가 작업",
"preview": "미리보기",
"preview_loading": "미리보기 불러오는 중...",
"preview_failed": "미리보기를 불러오지 못했습니다",
diff --git a/packages/views/locales/ru/editor.json b/packages/views/locales/ru/editor.json
index 7a62ee7599..1caf473397 100644
--- a/packages/views/locales/ru/editor.json
+++ b/packages/views/locales/ru/editor.json
@@ -56,6 +56,10 @@
"install_theme": "Установить тему",
"install_theme_failed": "Не удалось прочитать вложение. Попробуйте ещё раз чуть позже.",
"download_failed": "Не удалось получить ссылку для скачивания. Повторите попытку через некоторое время.",
+ "copy_contents": "Скопировать содержимое",
+ "contents_copied": "Содержимое скопировано",
+ "copy_failed": "Не удалось скопировать содержимое",
+ "more_actions": "Другие действия",
"preview": "Предпросмотр",
"preview_loading": "Загрузка предпросмотра…",
"preview_failed": "Не удалось загрузить предпросмотр",
diff --git a/packages/views/locales/zh-Hans/editor.json b/packages/views/locales/zh-Hans/editor.json
index fe7df4868f..08305a60c8 100644
--- a/packages/views/locales/zh-Hans/editor.json
+++ b/packages/views/locales/zh-Hans/editor.json
@@ -56,6 +56,10 @@
"install_theme": "安装主题",
"install_theme_failed": "无法读取附件,请稍后重试。",
"download_failed": "下载链接获取失败,请稍后重试。",
+ "copy_contents": "复制全文",
+ "contents_copied": "已复制全文",
+ "copy_failed": "无法复制全文",
+ "more_actions": "更多操作",
"preview": "预览",
"preview_loading": "加载预览中…",
"preview_failed": "预览加载失败",
diff --git a/packages/views/locales/zh-Hant/editor.json b/packages/views/locales/zh-Hant/editor.json
index bf01d5019b..a28d17b51b 100644
--- a/packages/views/locales/zh-Hant/editor.json
+++ b/packages/views/locales/zh-Hant/editor.json
@@ -56,6 +56,10 @@
"install_theme": "安裝主題",
"install_theme_failed": "無法讀取附件,請稍後再試。",
"download_failed": "下載連結獲取失敗,請稍後重試。",
+ "copy_contents": "複製全文",
+ "contents_copied": "已複製全文",
+ "copy_failed": "無法複製全文",
+ "more_actions": "更多操作",
"preview": "預覽",
"preview_loading": "載入預覽中…",
"preview_failed": "預覽載入失敗",