Skip to content

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

Go

fix(editor): keep image attachment actions clear of thumbnails (#10988)

Frezc1c9d060cf8e7
diff --git a/e2e/image-attachment-toolbar.spec.ts b/e2e/image-attachment-toolbar.spec.ts
new file mode 100644
index 0000000000..1ca6f586cd
--- /dev/null
+++ b/e2e/image-attachment-toolbar.spec.ts
@@ -0,0 +1,73 @@
+import { expect, test, type Page } from "@playwright/test";
+import type { TestApiClient } from "./fixtures";
+import { createTestApi, loginAsDefault } from "./helpers";
+
+async function imageMarkdown(page: Page, alt: string, width: number, height: number) {
+ const url = `https://fixture-images.invalid/${width}x${height}.svg`;
+ await page.route(url, (route) => route.fulfill({
+ contentType: "image/svg+xml",
+ body: `<svg xmlns="http://www.w3.org/2000/svg" width="${width}" height="${height}"><rect width="100%" height="100%" fill="royalblue"/></svg>`,
+ }));
+ return `![${alt}](${url})`;
+}
+
+test.describe("image attachment toolbar", () => {
+ let api: TestApiClient;
+ let workspaceSlug: string;
+
+ test.beforeEach(async ({ page, baseURL }) => {
+ const local = (url: string) => ["localhost", "127.0.0.1", "[::1]"].includes(new URL(url).hostname);
+ const apiBase = process.env.NEXT_PUBLIC_API_URL || `http://localhost:${process.env.PORT || "8080"}`;
+ test.skip(!baseURL || !local(baseURL) || !local(apiBase), "Local fixtures only");
+ api = await createTestApi();
+ workspaceSlug = await loginAsDefault(page);
+ });
+
+ test.afterEach(async () => {
+ await api?.cleanup();
+ });
+
+ test("can open a tall editor image when neither side has room", async ({ page }) => {
+ await page.setViewportSize({ width: 1280, height: 640 });
+ const description = await imageMarkdown(page, "Tall editor image", 420, 1800);
+ const issue = await api.createIssue("Tall image toolbar", { description });
+ await page.goto(`/${workspaceSlug}/issues/${issue.identifier}`);
+
+ const image = page.locator(".ProseMirror").getByAltText("Tall editor image");
+ await expect.poll(() => image.evaluate((img: HTMLImageElement) => img.naturalHeight)).toBe(1800);
+ await image.evaluate((img) => {
+ img.scrollIntoView({ block: "start" });
+ const scroller = img.closest<HTMLElement>("[data-tab-scroll-root]")!;
+ scroller.scrollTop += img.getBoundingClientRect().top + 16;
+ });
+ const bounds = (await image.boundingBox())!;
+ expect(bounds.y).toBeLessThan(0);
+ expect(bounds.y + bounds.height).toBeGreaterThan(640);
+
+ await image.hover({ position: { x: 24, y: 220 } });
+ const view = image.locator("..").getByRole("button", { name: "View image" });
+ await expect(view).toBeInViewport({ ratio: 1 });
+ await view.click();
+ await expect(page.getByRole("dialog")).toBeVisible();
+ });
+
+ test("keeps the table width when a small image toolbar is hidden", async ({ page }) => {
+ const image = await imageMarkdown(page, "Small table image", 24, 18);
+ const issue = await api.createIssue("Table image toolbar");
+ const comment = await api.createComment(issue.id, `| Text | Image |\n| --- | --- |\n| Content | ${image} |`);
+ await page.goto(`/${workspaceSlug}/issues/${issue.identifier}`);
+
+ const tableWrapper = page.locator(`[data-comment-content="${comment.id}"] .tableWrapper`);
+ const thumbnail = tableWrapper.getByAltText("Small table image");
+ await expect.poll(() => thumbnail.evaluate((img: HTMLImageElement) => img.naturalWidth)).toBe(24);
+ await tableWrapper.evaluate((wrapper) => {
+ wrapper.style.width = "340px";
+ wrapper.querySelector("table")!.style.tableLayout = "fixed";
+ wrapper.querySelector<HTMLElement>("th:last-child")!.style.width = "90px";
+ });
+
+ const toolbar = thumbnail.locator("..").locator(".image-toolbar");
+ await expect(toolbar).toHaveCSS("opacity", "0");
+ await expect.poll(() => tableWrapper.evaluate((wrapper) => wrapper.scrollWidth - wrapper.clientWidth)).toBe(0);
+ });
+});
diff --git a/packages/views/editor/attachment.test.tsx b/packages/views/editor/attachment.test.tsx
index 187012a951..c17fa0efff 100644
--- a/packages/views/editor/attachment.test.tsx
+++ b/packages/views/editor/attachment.test.tsx
@@ -254,6 +254,38 @@ describe("Attachment — image dispatch", () => {
expect(onDelete).toHaveBeenCalled();
});
+ it("keeps the editable image toolbar open after a touch tap until tapping outside", () => {
+ const onDelete = vi.fn();
+ const { container } = renderWithQuery(
+ <Attachment
+ attachment={{ kind: "record", attachment: makeRecord() }}
+ editable
+ onDelete={onDelete}
+ />,
+ );
+ const image = screen.getByRole("img", { name: "shot.png" });
+ const trash = screen.getByRole("button", { name: "Delete" });
+ const toolbar = trash.closest(".image-toolbar");
+ const touch = { pointerId: 1, pointerType: "touch" };
+
+ expect(toolbar).not.toHaveAttribute("data-placement");
+ fireEvent.pointerOver(image, touch);
+ fireEvent.pointerDown(image, touch);
+ fireEvent.pointerUp(image, touch);
+ fireEvent.pointerOut(image, touch);
+ fireEvent.click(image);
+
+ expect(toolbar).toHaveAttribute("data-placement");
+ fireEvent.pointerDown(trash, touch);
+ fireEvent.pointerUp(trash, touch);
+ fireEvent.pointerOut(trash, touch);
+ fireEvent.click(trash);
+ expect(onDelete).toHaveBeenCalledOnce();
+
+ fireEvent.pointerDown(container, touch);
+ expect(toolbar).not.toHaveAttribute("data-placement");
+ });
+
it("url-only image resolves to a record via context and uses its id for download", () => {
const att = makeRecord({
filename: "from-resolver.png",
@@ -1287,13 +1319,14 @@ describe("image download feedback", () => {
downloadMock.mockReturnValueOnce(pending.promise);
renderWithQuery(<Attachment attachment={{ kind: "record", attachment: makeRecord() }} />);
const button = screen.getByRole("button", { name: "Download" });
+ const toolbar = button.closest(".image-toolbar");
fireEvent.click(button);
expect(button).toBeDisabled();
expect(button).toHaveAttribute("aria-busy", "true");
expect(button.querySelector(".animate-spin")).toBeInTheDocument();
- expect(button.closest(".image-toolbar")).toHaveStyle({ opacity: "1" });
+ expect(toolbar).toHaveAttribute("data-placement");
fireEvent.click(button);
expect(downloadMock).toHaveBeenCalledExactlyOnceWith("att-1");
@@ -1302,6 +1335,7 @@ describe("image download feedback", () => {
expect(button).toBeEnabled();
expect(button).toHaveAttribute("aria-busy", "false");
expect(button.querySelector(".animate-spin")).toBeNull();
+ expect(toolbar).not.toHaveAttribute("data-placement");
});
it("keeps sibling images available while preparing a download", async () => {
diff --git a/packages/views/editor/attachment.tsx b/packages/views/editor/attachment.tsx
index a1029c678b..e1e3c5d8f8 100644
--- a/packages/views/editor/attachment.tsx
+++ b/packages/views/editor/attachment.tsx
@@ -35,7 +35,8 @@ import {
Maximize2,
Trash2,
} from "@multica/ui/icons";
-import { useCallback, useState, type CSSProperties, type ReactNode } from "react";
+import { useCallback, useEffect, useRef, useState, type CSSProperties, type ReactNode } from "react";
+import { autoUpdate, computePosition, flip, hide, offset, shift } from "@floating-ui/dom";
import { toast } from "sonner";
import { cn } from "@multica/ui/lib/utils";
import { copyText } from "@multica/ui/lib/clipboard";
@@ -536,9 +537,79 @@ function ImageAttachmentView({
className,
}: ImageAttachmentViewProps) {
const { t } = useT("editor");
- const { downloading, handleDownload } = useAttachmentDownloadState(onDownload);
const copyLink = useCopyAttachmentLink();
const handleCopyLink = () => copyLink(linkUrl);
+ const figureRef = useRef<HTMLSpanElement>(null);
+ const toolbarRef = useRef<HTMLSpanElement>(null);
+ const [toolbarActivation, setToolbarActivation] = useState<"hover-or-focus" | "touch" | null>(null);
+ const showToolbar = () => setToolbarActivation((activation) => activation ?? "hover-or-focus");
+ const hideToolbarIfIdle = (event?: "pointerleave" | "blur") => {
+ const figure = figureRef.current;
+ if (!figure) return;
+ const hovered = event !== "pointerleave" && figure.matches(":hover");
+ const keyboardFocused = event !== "blur" && figure.querySelector(":focus-visible") !== null;
+ setToolbarActivation((activation) => {
+ // A touch tap emits pointerleave as soon as the finger lifts.
+ if (activation === "touch") return event === "blur" ? null : activation;
+ return hovered || keyboardFocused ? activation : null;
+ });
+ };
+ // Chromium can omit pointerleave when the hovered download button becomes disabled.
+ const { downloading, handleDownload } = useAttachmentDownloadState(() =>
+ onDownload()?.finally(hideToolbarIfIdle),
+ );
+ const hasToolbar = !uploading && !!src;
+ const toolbarOpen = hasToolbar && (toolbarActivation !== null || downloading);
+
+ useEffect(() => {
+ const figure = figureRef.current;
+ if (toolbarActivation !== "touch" || !figure) return;
+
+ const onOutsidePointerDown = (event: PointerEvent) => {
+ if (!event.composedPath().includes(figure)) {
+ setToolbarActivation((activation) => activation === "touch" ? null : activation);
+ }
+ };
+ const ownerDocument = figure.ownerDocument;
+ ownerDocument.addEventListener("pointerdown", onOutsidePointerDown, true);
+ return () => ownerDocument.removeEventListener("pointerdown", onOutsidePointerDown, true);
+ }, [toolbarActivation]);
+
+ useEffect(() => {
+ const figure = figureRef.current;
+ const toolbar = toolbarRef.current;
+ if (!toolbarOpen || !figure || !toolbar) return;
+
+ const boundary = { padding: 4, altBoundary: true };
+ let active = true;
+ toolbar.dataset.placement = "pending";
+ const cleanup = autoUpdate(figure, toolbar, () => {
+ void computePosition(figure, toolbar, {
+ strategy: "fixed",
+ placement: "top",
+ middleware: [
+ offset(4),
+ flip({ ...boundary, crossAxis: false }),
+ shift(({ rects }) => ({
+ ...boundary,
+ // After trying both sides, a tall figure can spare room for reachable controls.
+ crossAxis: rects.reference.height >= rects.floating.height * 2,
+ })),
+ hide(),
+ ],
+ }).then(({ x, y, placement, middlewareData }) => {
+ if (!active) return;
+ toolbar.style.setProperty("--image-toolbar-x", `${x}px`);
+ toolbar.style.setProperty("--image-toolbar-y", `${y}px`);
+ toolbar.dataset.placement = middlewareData.hide?.referenceHidden ? "pending" : placement;
+ });
+ });
+ return () => {
+ active = false;
+ cleanup();
+ delete toolbar.dataset.placement;
+ };
+ }, [toolbarOpen]);
// Click on figure opens the preview only in non-editor / non-uploading
// surfaces — inside the editor we let ProseMirror own the click for
@@ -572,6 +643,7 @@ function ImageAttachmentView({
return (
<span ref={scopeRef} className="image-node">
<span
+ ref={figureRef}
className={cn(
"image-figure",
selected && editable && "image-selected",
@@ -583,6 +655,17 @@ function ImageAttachmentView({
style={sizeStyle}
contentEditable={false}
onClick={clickable ? onView : undefined}
+ onPointerEnter={(event) => {
+ if (!editable || event.pointerType !== "touch") showToolbar();
+ }}
+ onPointerUp={(event) => {
+ if (editable && hasToolbar && event.pointerType === "touch") setToolbarActivation("touch");
+ }}
+ onPointerLeave={() => hideToolbarIfIdle("pointerleave")}
+ onFocus={showToolbar}
+ onBlur={(event) => {
+ if (!event.currentTarget.contains(event.relatedTarget)) hideToolbarIfIdle("blur");
+ }}
>
<img
ref={imgRef}
@@ -598,10 +681,10 @@ function ImageAttachmentView({
onLoad={() => setLoadedSrc(src)}
onError={() => setLoadedSrc(src)}
/>
- {!uploading && src && (
+ {hasToolbar && (
<span
+ ref={toolbarRef}
className="image-toolbar"
- style={downloading ? { opacity: 1 } : undefined}
onMouseDown={(e) => e.stopPropagation()}
onClick={(e) => e.stopPropagation()}
>
diff --git a/packages/views/editor/styles/attachment.css b/packages/views/editor/styles/attachment.css
index fa214437b9..d4193b68de 100644
--- a/packages/views/editor/styles/attachment.css
+++ b/packages/views/editor/styles/attachment.css
@@ -92,22 +92,49 @@
}
.image-toolbar {
+ /* Keep the resting controls near their image so tabbing to them scrolls it into view. */
position: absolute;
- top: 0.5rem;
- right: 0.5rem;
+ top: 0;
+ inset-inline-end: 0;
display: flex;
+ width: max-content;
gap: 1px;
padding: 0.25rem;
background: color-mix(in srgb, black 75%, transparent);
backdrop-filter: blur(8px);
border-radius: var(--radius);
opacity: 0;
- transition: opacity 0.15s;
- z-index: 1;
+ pointer-events: none;
+ z-index: 30;
+}
+
+.image-toolbar[data-placement] {
+ position: fixed;
+ inset-inline-end: auto;
+ top: var(--image-toolbar-y, 0);
+ left: var(--image-toolbar-x, 0);
}
-.image-figure:hover .image-toolbar {
+.image-toolbar:is([data-placement="top"], [data-placement="bottom"]) {
opacity: 1;
+ pointer-events: auto;
+ transition: opacity 0.15s;
+}
+
+/* Keep the gap between the image and its toolbar hoverable. */
+.image-toolbar::after {
+ position: absolute;
+ inset-inline: 0;
+ height: 4px;
+ content: "";
+}
+
+.image-toolbar[data-placement="top"]::after {
+ top: 100%;
+}
+
+.image-toolbar[data-placement="bottom"]::after {
+ bottom: 100%;
}
.image-toolbar button {
@@ -172,15 +199,6 @@
max-height: 25rem;
}
-/* A thumbnail can be narrower than its toolbar, so the toolbar grows from
- the left edge into the open space instead of past the column's edge. */
-[data-comment-images="thumbnails"] [data-comment-image-list] .image-toolbar,
-[data-comment-images] .ProseMirror .image-toolbar {
- top: 0.25rem;
- left: 0.25rem;
- right: auto;
-}
-
/* Comment composers, whatever the preference: an image keeps its place in
the text as a small thumbnail, so what is being written stays in view. */
[data-comment-images] .ProseMirror .image-node {