Skip to content

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

Go

refactor(editor): unify attachment rendering into a single <Attachment> component (#2850)

Naiyuan Qing39f43a9a9828
diff --git a/packages/ui/markdown/Markdown.tsx b/packages/ui/markdown/Markdown.tsx
index 4958f9cd53..8380450962 100644
--- a/packages/ui/markdown/Markdown.tsx
+++ b/packages/ui/markdown/Markdown.tsx
@@ -60,6 +60,20 @@ export interface MarkdownProps {
* When provided, enables file card preprocessing and rendering.
*/
cdnDomain?: string
+ /**
+ * Optional override for the image renderer. When provided, replaces the
+ * default `<img>` with constrained sizing. The views-package wrapper uses
+ * this to inject the unified `<Attachment>` component so chat messages get
+ * the same hover toolbar / lightbox / preview-modal treatment as comments.
+ */
+ renderImage?: (props: { src: string; alt: string }) => React.ReactNode
+ /**
+ * Optional override for the file-card renderer. When provided, replaces
+ * the simplified card chrome (filename + download button) with whatever
+ * the caller supplies. Used the same way as `renderImage` to bridge into
+ * the views-package `<Attachment>` component.
+ */
+ renderFileCard?: (props: { href: string; filename: string }) => React.ReactNode
}
// Sanitization schema — extends GitHub defaults to allow code highlighting classes
@@ -113,6 +127,8 @@ function createComponents(
onUrlClick?: (url: string) => void,
onFileClick?: (path: string) => void,
renderMention?: (props: { type: string; id: string }) => React.ReactNode,
+ renderImage?: (props: { src: string; alt: string }) => React.ReactNode,
+ renderFileCard?: (props: { href: string; filename: string }) => React.ReactNode,
): Partial<Components> {
const baseComponents: Partial<Components> = {
// FileCard: intercept <div data-type="fileCard"> from preprocessFileCards
@@ -122,6 +138,9 @@ function createComponents(
const rawHref = (node?.properties?.dataHref as string) || ''
const href = isAllowedFileCardHref(rawHref) ? rawHref : ''
const filename = (node?.properties?.dataFilename as string) || ''
+ if (renderFileCard) {
+ return <>{renderFileCard({ href, filename })}</>
+ }
return (
<div className="my-1 flex items-center gap-2 rounded-md border border-border bg-muted/50 px-2.5 py-1 transition-colors hover:bg-muted">
<FileText className="size-4 shrink-0 text-muted-foreground" />
@@ -143,14 +162,19 @@ function createComponents(
return <div {...props}>{children}</div>
},
// Images: render uploaded images with constrained sizing
- img: ({ src, alt }) => (
- <img
- src={src}
- alt={alt ?? ""}
- className="max-w-full h-auto rounded-md my-2"
- loading="lazy"
- />
- ),
+ img: ({ src, alt }) => {
+ if (renderImage) {
+ return <>{renderImage({ src: typeof src === 'string' ? src : '', alt: alt ?? '' })}</>
+ }
+ return (
+ <img
+ src={src}
+ alt={alt ?? ""}
+ className="max-w-full h-auto rounded-md my-2"
+ loading="lazy"
+ />
+ )
+ },
// Links: Make clickable with callbacks, or render as mention
a: ({ href, children }) => {
// Mention links: mention://member/id, mention://agent/id, mention://issue/id, mention://all/all
@@ -384,11 +408,13 @@ export function Markdown({
onUrlClick,
onFileClick,
renderMention,
+ renderImage,
+ renderFileCard,
cdnDomain
}: MarkdownProps): React.JSX.Element {
const components = React.useMemo(
- () => createComponents(mode, onUrlClick, onFileClick, renderMention),
- [mode, onUrlClick, onFileClick, renderMention]
+ () => createComponents(mode, onUrlClick, onFileClick, renderMention, renderImage, renderFileCard),
+ [mode, onUrlClick, onFileClick, renderMention, renderImage, renderFileCard]
)
// Preprocess: convert mention shortcodes, raw URLs, and file cards to renderable content
diff --git a/packages/views/chat/components/chat-message-list.tsx b/packages/views/chat/components/chat-message-list.tsx
index 0c21266777..e95eac66a5 100644
--- a/packages/views/chat/components/chat-message-list.tsx
+++ b/packages/views/chat/components/chat-message-list.tsx
@@ -22,6 +22,7 @@ import { useAutoScroll } from "@multica/ui/hooks/use-auto-scroll";
import { taskMessagesOptions } from "@multica/core/chat/queries";
import { Markdown } from "@multica/views/common/markdown";
import { copyMarkdown } from "../../editor";
+import { AttachmentList } from "../../issues/components/comment-card";
import type { AgentAvailability } from "@multica/core/agents";
import type { ChatMessage, ChatPendingTask, TaskMessagePayload, TaskFailureReason } from "@multica/core/types";
import type { ChatTimelineItem } from "@multica/core/chat";
@@ -155,8 +156,13 @@ function MessageBubble({ message, isPending }: { message: ChatMessage; isPending
* Neutralise prose's leading/trailing margin so single-line
* bubbles stay as compact as the plain-text version used to. */}
<div className="prose prose-sm dark:prose-invert max-w-none [&>*:first-child]:mt-0 [&>*:last-child]:mb-0">
- <Markdown>{message.content}</Markdown>
+ <Markdown attachments={message.attachments}>{message.content}</Markdown>
</div>
+ <AttachmentList
+ attachments={message.attachments}
+ content={message.content}
+ className="mt-1.5"
+ />
</div>
</div>
);
@@ -202,12 +208,16 @@ function AssistantMessage({
return (
<div className="w-full space-y-1.5">
{timeline.length > 0 ? (
- <TimelineView items={timeline} />
+ <TimelineView items={timeline} attachments={message.attachments} />
) : (
<div className="text-sm leading-relaxed prose prose-sm dark:prose-invert max-w-none">
- <Markdown>{message.content}</Markdown>
+ <Markdown attachments={message.attachments}>{message.content}</Markdown>
</div>
)}
+ <AttachmentList
+ attachments={message.attachments}
+ content={message.content}
+ />
<MessageFooter
message={message}
timeline={timeline}
@@ -382,9 +392,11 @@ function FailureBubble({
function TimelineView({
items,
isStreaming,
+ attachments,
}: {
items: ChatTimelineItem[];
isStreaming?: boolean;
+ attachments?: import("@multica/core/types").Attachment[];
}) {
const { preface, middle, final } = splitTimeline(items);
@@ -392,15 +404,23 @@ function TimelineView({
<>
{preface.length > 0 && (
<div className="text-sm leading-relaxed prose prose-sm dark:prose-invert max-w-none">
- <Markdown>{preface.map((t) => t.content ?? "").join("")}</Markdown>
+ <Markdown attachments={attachments}>
+ {preface.map((t) => t.content ?? "").join("")}
+ </Markdown>
</div>
)}
{middle.length > 0 && (
- <OuterProcessFold items={middle} defaultOpen={!!isStreaming} />
+ <OuterProcessFold
+ items={middle}
+ defaultOpen={!!isStreaming}
+ attachments={attachments}
+ />
)}
{final.length > 0 && (
<div className="text-sm leading-relaxed prose prose-sm dark:prose-invert max-w-none">
- <Markdown>{final.map((t) => t.content ?? "").join("")}</Markdown>
+ <Markdown attachments={attachments}>
+ {final.map((t) => t.content ?? "").join("")}
+ </Markdown>
</div>
)}
</>
@@ -410,9 +430,11 @@ function TimelineView({
function OuterProcessFold({
items,
defaultOpen,
+ attachments,
}: {
items: ChatTimelineItem[];
defaultOpen?: boolean;
+ attachments?: import("@multica/core/types").Attachment[];
}) {
const { t } = useT("chat");
// useState seeds once at mount — subsequent renders never overwrite the
@@ -433,7 +455,7 @@ function OuterProcessFold({
<div className="mt-1 rounded-lg border bg-muted/20 p-2 space-y-0.5">
{items.map((item) =>
item.type === "text" ? (
- <MiddleTextRow key={item.seq} item={item} />
+ <MiddleTextRow key={item.seq} item={item} attachments={attachments} />
) : (
<ItemRow key={item.seq} item={item} />
),
@@ -448,10 +470,16 @@ function OuterProcessFold({
// down-shifted (xs / muted) so it reads as part of the agent's process,
// not the final answer — the final answer renders below the fold at full
// prose size.
-function MiddleTextRow({ item }: { item: ChatTimelineItem }) {
+function MiddleTextRow({
+ item,
+ attachments,
+}: {
+ item: ChatTimelineItem;
+ attachments?: import("@multica/core/types").Attachment[];
+}) {
return (
<div className="py-0.5 text-xs text-muted-foreground prose prose-sm dark:prose-invert max-w-none [&>*:first-child]:mt-0 [&>*:last-child]:mb-0">
- <Markdown>{item.content ?? ""}</Markdown>
+ <Markdown attachments={attachments}>{item.content ?? ""}</Markdown>
</div>
);
}
diff --git a/packages/views/common/markdown.tsx b/packages/views/common/markdown.tsx
index 1be0b15153..dd77df44a0 100644
--- a/packages/views/common/markdown.tsx
+++ b/packages/views/common/markdown.tsx
@@ -7,11 +7,25 @@ import {
type RenderMode,
} from "@multica/ui/markdown";
import { useConfigStore } from "@multica/core/config";
+import type { Attachment as AttachmentRecord } from "@multica/core/types";
import { IssueMentionCard } from "../issues/components/issue-mention-card";
+import {
+ Attachment as AttachmentRenderer,
+ AttachmentDownloadProvider,
+} from "../editor";
export type { RenderMode };
-export type MarkdownProps = MarkdownBaseProps;
+export interface MarkdownProps extends MarkdownBaseProps {
+ /**
+ * Attachments associated with the surrounding entity (chat message, skill
+ * file). When passed, the renderer resolves inline image / file-card URLs
+ * to full attachment records via AttachmentDownloadProvider, unlocking the
+ * unified hover toolbar / lightbox / preview-modal behavior used in
+ * editor surfaces.
+ */
+ attachments?: AttachmentRecord[];
+}
/**
* Default renderMention that delegates to IssueMentionCard for issue mentions
@@ -30,13 +44,58 @@ function defaultRenderMention({
return null;
}
+function renderImage({ src, alt }: { src: string; alt: string }): React.ReactNode {
+ return (
+ <AttachmentRenderer
+ attachment={{
+ kind: "url",
+ url: src,
+ filename: alt,
+ // chat / skill markdown `![]()` is structurally an image. Without
+ // forceKind, empty/descriptive alt strings would route to the
+ // file-card chrome via getPreviewKind autodetect.
+ forceKind: "image",
+ }}
+ />
+ );
+}
+
+function renderFileCard({
+ href,
+ filename,
+}: {
+ href: string;
+ filename: string;
+}): React.ReactNode {
+ return (
+ <AttachmentRenderer
+ attachment={{ kind: "url", url: href, filename }}
+ />
+ );
+}
+
/**
- * App-level Markdown wrapper that injects IssueMentionCard via renderMention
- * and cdnDomain from the config store for file card rendering.
+ * App-level Markdown wrapper. Injects:
+ * - IssueMentionCard for issue mentions
+ * - cdnDomain from the config store (drives fileCard preprocessing)
+ * - unified <Attachment> as the image / file-card renderer
+ * - AttachmentDownloadProvider so url → record resolution works inside
+ * the injected <Attachment> components
*/
export function Markdown(props: MarkdownProps): React.JSX.Element {
const cdnDomain = useConfigStore((s) => s.cdnDomain);
- return <MarkdownBase renderMention={defaultRenderMention} cdnDomain={cdnDomain} {...props} />;
+ const { attachments, ...rest } = props;
+ return (
+ <AttachmentDownloadProvider attachments={attachments}>
+ <MarkdownBase
+ renderMention={defaultRenderMention}
+ renderImage={renderImage}
+ renderFileCard={renderFileCard}
+ cdnDomain={cdnDomain}
+ {...rest}
+ />
+ </AttachmentDownloadProvider>
+ );
}
export const MemoizedMarkdown = React.memo(Markdown);
diff --git a/packages/views/editor/attachment-block.test.tsx b/packages/views/editor/attachment-block.test.tsx
deleted file mode 100644
index fd1c57c4aa..0000000000
--- a/packages/views/editor/attachment-block.test.tsx
+++ /dev/null
@@ -1,136 +0,0 @@
-import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
-import { render, screen } from "@testing-library/react";
-import type { ReactElement } from "react";
-import { QueryClient, QueryClientProvider } from "@tanstack/react-query";
-
-const { getAttachmentTextContentMock } = vi.hoisted(() => ({
- getAttachmentTextContentMock: vi.fn(),
-}));
-
-vi.mock("@multica/core/api", () => ({
- api: { getAttachmentTextContent: getAttachmentTextContentMock },
- PreviewTooLargeError: class extends Error {},
- PreviewUnsupportedError: class extends Error {},
-}));
-
-vi.mock("../i18n", () => ({
- useT: () => ({
- t: (sel: (s: Record<string, Record<string, string>>) => string) =>
- sel({
- image: { download: "Download" },
- attachment: {
- preview: "Preview",
- preview_loading: "Loading preview…",
- preview_failed: "Couldn't load preview",
- open_in_new_tab: "Open in new tab",
- },
- file_card: { uploading: "Uploading {{filename}}" },
- }),
- }),
-}));
-
-vi.mock("../navigation", () => ({
- useNavigation: () => ({
- push: vi.fn(),
- replace: vi.fn(),
- back: vi.fn(),
- pathname: "/acme/issues",
- searchParams: new URLSearchParams(),
- openInNewTab: vi.fn(),
- getShareableUrl: (p: string) => `https://app.example${p}`,
- }),
-}));
-
-vi.mock("@multica/core/paths", async (importOriginal) => {
- const actual = await importOriginal<typeof import("@multica/core/paths")>();
- return {
- ...actual,
- useWorkspaceSlug: () => "acme",
- useWorkspacePaths: () => actual.paths.workspace("acme"),
- };
-});
-
-import { AttachmentBlock } from "./attachment-block";
-
-function renderWithQuery(ui: ReactElement) {
- const qc = new QueryClient({
- defaultOptions: { queries: { retry: false, gcTime: 0 } },
- });
- return render(<QueryClientProvider client={qc}>{ui}</QueryClientProvider>);
-}
-
-beforeEach(() => vi.clearAllMocks());
-afterEach(() => vi.restoreAllMocks());
-
-describe("AttachmentBlock — dispatcher", () => {
- it("routes html + attachmentId to HtmlAttachmentPreview (no file-card chrome)", () => {
- getAttachmentTextContentMock.mockResolvedValueOnce({
- text: "<p>chart</p>",
- originalContentType: "text/html",
- });
- renderWithQuery(
- <AttachmentBlock
- filename="report.html"
- contentType="text/html"
- attachmentId="att-1"
- href="https://cdn.example/report.html"
- onPreview={() => {}}
- onDownload={() => {}}
- />,
- );
- // HtmlAttachmentPreview never renders the filename row — that's the
- // file-card chrome it replaces.
- expect(screen.queryByText("report.html")).toBeNull();
- // Toolbar shows Preview + Download only — attachments are files, not
- // inline source snippets, so there is no Copy code button.
- expect(screen.getByTitle("Preview")).toBeTruthy();
- expect(screen.getByTitle("Download")).toBeTruthy();
- expect(screen.queryByTitle("Copy code")).toBeNull();
- });
-
- it("routes html WITHOUT attachmentId to AttachmentCard (URL-only is chrome-only)", () => {
- renderWithQuery(
- <AttachmentBlock
- filename="report.html"
- contentType="text/html"
- href="https://cdn.example/report.html"
- onPreview={() => {}}
- onDownload={() => {}}
- />,
- );
- expect(screen.getByText("report.html")).toBeTruthy();
- expect(document.querySelector("iframe")).toBeNull();
- });
-
- it("routes html while uploading to AttachmentCard (no iframe before upload finishes)", () => {
- renderWithQuery(
- <AttachmentBlock
- filename="report.html"
- contentType="text/html"
- attachmentId="att-1"
- href="https://cdn.example/report.html"
- uploading
- onPreview={() => {}}
- onDownload={() => {}}
- />,
- );
- // Uploading state surfaces the chrome row with the upload template.
- expect(screen.getByText("Uploading {{filename}}")).toBeTruthy();
- expect(document.querySelector("iframe")).toBeNull();
- });
-
- it("routes non-html kinds (pdf, image, other) to AttachmentCard", () => {
- renderWithQuery(
- <AttachmentBlock
- filename="manual.pdf"
- contentType="application/pdf"
- attachmentId="att-1"
- href="https://cdn.example/manual.pdf"
- onPreview={() => {}}
- onDownload={() => {}}
- />,
- );
- expect(screen.getByText("manual.pdf")).toBeTruthy();
- expect(document.querySelector("iframe")).toBeNull();
- });
-});
diff --git a/packages/views/editor/attachment-block.tsx b/packages/views/editor/attachment-block.tsx
deleted file mode 100644
index 5b178018c9..0000000000
--- a/packages/views/editor/attachment-block.tsx
+++ /dev/null
@@ -1,42 +0,0 @@
-"use client";
-
-/**
- * AttachmentBlock — thin dispatcher choosing the renderer for an attachment.
- *
- * Centralizes the kind-aware routing that previously lived inside
- * AttachmentCard (and earlier still, was duplicated across three call sites).
- * Three entry points render attachments and all must agree on which kinds get
- * which visual treatment, otherwise feature work has to be repeated three
- * times — see MUL-2330, where the inline HTML preview was missed on the
- * standalone path.
- *
- * Current routing:
- * - kind === "html" + attachmentId + !uploading → HtmlAttachmentPreview
- * (independent iframe + hover toolbar, no file-card chrome)
- * - everything else → AttachmentCard (icon + filename + Eye/Download row)
- *
- * Props match AttachmentCardProps exactly so callers stay as-is — only the
- * import changes.
- */
-
-import { getPreviewKind } from "./utils/preview";
-import { AttachmentCard, type AttachmentCardProps } from "./attachment-card";
-import { HtmlAttachmentPreview } from "./html-attachment-preview";
-
-export type AttachmentBlockProps = AttachmentCardProps;
-
-export function AttachmentBlock(props: AttachmentBlockProps) {
- const { filename, contentType = "", attachmentId, uploading } = props;
- const kind = filename ? getPreviewKind(contentType, filename) : null;
- if (kind === "html" && attachmentId && !uploading) {
- return (
- <HtmlAttachmentPreview
- attachmentId={attachmentId}
- filename={filename}
- onPreview={props.onPreview}
- onDownload={props.onDownload}
- />
- );
- }
- return <AttachmentCard {...props} />;
-}
diff --git a/packages/views/editor/attachment-card.tsx b/packages/views/editor/attachment-card.tsx
index cea2a2bdec..3ba7f6e350 100644
--- a/packages/views/editor/attachment-card.tsx
+++ b/packages/views/editor/attachment-card.tsx
@@ -3,17 +3,10 @@
/**
* AttachmentCard — shared file-card row UI (icon + filename + Eye + Download).
*
+ * Subcomponent of the unified `<Attachment>` dispatcher (see attachment.tsx).
* Rendered for every attachment kind that does not have a richer inline
- * renderer. Three call sites reach it indirectly through AttachmentBlock,
- * which picks the right component per kind:
- *
- * 1. `extensions/file-card.tsx` — Tiptap NodeView for `!file[name](url)`.
- * 2. `readonly-content.tsx` — readonly `<div data-type="fileCard">`.
- * 3. `comment-card.tsx` AttachmentList — standalone attachments not inlined.
- *
- * Kind-aware routing (e.g. HTML → inline iframe preview) lives in
- * AttachmentBlock — keep that decision out of this file so this stays a
- * single-purpose row UI.
+ * renderer (image / html). Kind-aware routing lives in `<Attachment>` — keep
+ * that decision out of this file so this stays a single-purpose row UI.
*/
import { Download, Eye, FileText, Loader2 } from "lucide-react";
diff --git a/packages/views/editor/attachment-preview-modal.test.tsx b/packages/views/editor/attachment-preview-modal.test.tsx
index a6e476aae6..a49774efc4 100644
--- a/packages/views/editor/attachment-preview-modal.test.tsx
+++ b/packages/views/editor/attachment-preview-modal.test.tsx
@@ -154,6 +154,28 @@ afterEach(() => {
});
describe("AttachmentPreviewModal — dispatch", () => {
+ it("renders an <img> centered in the modal for image content types", () => {
+ const att = makeAttachment({ filename: "shot.png", content_type: "image/png" });
+ render(<AttachmentPreviewModal source={{ kind: "full", attachment: att }} open onClose={() => {}} />);
+ const img = document.querySelector("img");
+ expect(img).toBeTruthy();
+ expect(img?.getAttribute("src")).toBe(att.download_url);
+ expect(img?.getAttribute("alt")).toBe(att.filename);
+ });
+
+ it("renders an <img> from a URL-only source for image filenames", () => {
+ const url = "https://cdn.example.test/orphan.png?Signature=s";
+ render(
+ <AttachmentPreviewModal
+ source={{ kind: "url", url, filename: "orphan.png" }}
+ open
+ onClose={() => {}}
+ />,
+ );
+ const img = document.querySelector("img");
+ expect(img?.getAttribute("src")).toBe(url);
+ });
+
it("renders a PDF iframe pointing at the signed download URL", () => {
const att = makeAttachment({ filename: "manual.pdf", content_type: "application/pdf" });
render(<AttachmentPreviewModal source={{ kind: "full", attachment: att }} open onClose={() => {}} />);
diff --git a/packages/views/editor/attachment-preview-modal.tsx b/packages/views/editor/attachment-preview-modal.tsx
index 240370df71..39e94a2555 100644
--- a/packages/views/editor/attachment-preview-modal.tsx
+++ b/packages/views/editor/attachment-preview-modal.tsx
@@ -3,9 +3,10 @@
/**
* AttachmentPreviewModal — full-screen inline preview for an attachment.
*
- * Sibling to the existing `ImageLightbox` (extensions/image-view.tsx) which
- * keeps owning images. This modal handles 6 other PreviewKinds:
+ * Single modal for every previewable kind. Handles 7 PreviewKinds:
*
+ * - image : <img className="object-contain"> centered in the modal frame.
+ * Replaces the previous standalone ImageLightbox.
* - pdf : <iframe src={download_url}> — relies on Chromium's PDFium
* plugin. On desktop, requires webPreferences.plugins=true
* (see apps/desktop/src/main/index.ts).
@@ -77,7 +78,7 @@ export type PreviewSource =
// PreviewKinds that can render from a URL-only source. Text-based kinds
// (markdown / html / text) need the /content proxy which is ID-keyed.
-const URL_ONLY_KINDS = new Set<PreviewKind>(["pdf", "video", "audio"]);
+const URL_ONLY_KINDS = new Set<PreviewKind>(["image", "pdf", "video", "audio"]);
// Normalized view used everywhere downstream of `useAttachmentPreview`.
// `attachmentId === null` signals URL-only mode (download falls back to
@@ -343,6 +344,16 @@ function PreviewContent({
}
switch (kind) {
+ case "image":
+ return (
+ <div className="flex h-full w-full items-center justify-center bg-black/40 p-4">
+ <img
+ src={state.mediaUrl}
+ alt={state.filename}
+ className="max-h-full max-w-full rounded-lg object-contain"
+ />
+ </div>
+ );
case "pdf":
return (
<iframe
diff --git a/packages/views/editor/attachment.test.tsx b/packages/views/editor/attachment.test.tsx
new file mode 100644
index 0000000000..6eb543962f
--- /dev/null
+++ b/packages/views/editor/attachment.test.tsx
@@ -0,0 +1,298 @@
+import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
+import { render, screen, fireEvent } from "@testing-library/react";
+import type { ReactElement, ReactNode } from "react";
+import { QueryClient, QueryClientProvider } from "@tanstack/react-query";
+import type { Attachment as AttachmentRecord } from "@multica/core/types";
+
+const {
+ getAttachmentTextContentMock,
+ downloadMock,
+ openExternalMock,
+ openByUrlMock,
+} = vi.hoisted(() => ({
+ getAttachmentTextContentMock: vi.fn(),
+ downloadMock: vi.fn(),
+ openExternalMock: vi.fn(),
+ openByUrlMock: vi.fn(),
+}));
+
+vi.mock("@multica/core/api", () => ({
+ api: { getAttachmentTextContent: getAttachmentTextContentMock },
+ PreviewTooLargeError: class extends Error {},
+ PreviewUnsupportedError: class extends Error {},
+}));
+
+vi.mock("./use-download-attachment", () => ({
+ useDownloadAttachment: () => downloadMock,
+}));
+
+vi.mock("../platform", () => ({
+ openExternal: openExternalMock,
+}));
+
+vi.mock("../i18n", () => ({
+ useT: () => ({
+ t: (sel: (s: Record<string, Record<string, string>>) => string) =>
+ sel({
+ image: {
+ view: "View",
+ download: "Download",
+ copy_link: "Copy link",
+ copy_link_failed: "Copy failed",
+ link_copied: "Link copied",
+ delete: "Delete",
+ },
+ attachment: {
+ preview: "Preview",
+ preview_loading: "Loading preview…",
+ preview_failed: "Couldn't load preview",
+ preview_unsupported: "This file type can't be previewed.",
+ preview_too_large: "File is too large to preview.",
+ open_in_new_tab: "Open in new tab",
+ close: "Close",
+ },
+ file_card: { uploading: "Uploading {{filename}}" },
+ }),
+ }),
+}));
+
+vi.mock("../navigation", () => ({
+ useNavigation: () => ({
+ push: vi.fn(),
+ replace: vi.fn(),
+ back: vi.fn(),
+ pathname: "/acme/issues",
+ searchParams: new URLSearchParams(),
+ openInNewTab: vi.fn(),
+ getShareableUrl: (p: string) => `https://app.example${p}`,
+ }),
+}));
+
+vi.mock("@multica/core/paths", async (importOriginal) => {
+ const actual = await importOriginal<typeof import("@multica/core/paths")>();
+ return {
+ ...actual,
+ useWorkspaceSlug: () => "acme",
+ useWorkspacePaths: () => actual.paths.workspace("acme"),
+ };
+});
+
+// Resolver mock — feeds the test-scoped attachments[] into the
+// useAttachmentDownloadResolver hook the component reads.
+const resolverState: { attachments: AttachmentRecord[] } = { attachments: [] };
+vi.mock("./attachment-download-context", () => ({
+ useAttachmentDownloadResolver: () => ({
+ resolveAttachmentId: (url: string) =>
+ resolverState.attachments.find((a) => a.url === url)?.id,
+ resolveAttachment: (url: string) =>
+ resolverState.attachments.find((a) => a.url === url),
+ openByUrl: openByUrlMock,
+ }),
+ AttachmentDownloadProvider: ({ children }: { children: ReactNode }) =>
+ <>{children}</>,
+}));
+
+import { Attachment } from "./attachment";
+
+function makeRecord(overrides: Partial<AttachmentRecord> = {}): AttachmentRecord {
+ return {
+ id: "att-1",
+ workspace_id: "ws-1",
+ issue_id: null,
+ comment_id: null,
+ chat_session_id: null,
+ chat_message_id: null,
+ uploader_type: "member",
+ uploader_id: "u-1",
+ filename: "shot.png",
+ url: "https://cdn.example.test/att-1.png",
+ download_url: "https://cdn.example.test/att-1.png?Signature=s",
+ content_type: "image/png",
+ size_bytes: 1024,
+ created_at: "2026-05-13T00:00:00Z",
+ ...overrides,
+ };
+}
+
+function renderWithQuery(ui: ReactElement) {
+ const qc = new QueryClient({
+ defaultOptions: { queries: { retry: false, gcTime: 0 } },
+ });
+ return render(<QueryClientProvider client={qc}>{ui}</QueryClientProvider>);
+}
+
+beforeEach(() => {
+ vi.clearAllMocks();
+ resolverState.attachments = [];
+});
+
+afterEach(() => {
+ vi.restoreAllMocks();
+});
+
+describe("Attachment — image dispatch", () => {
+ it("record image renders <img> with hover toolbar (View/Download/Copy)", () => {
+ const att = makeRecord();
+ renderWithQuery(<Attachment attachment={{ kind: "record", attachment: att }} />);
+ const img = document.querySelector("img");
+ expect(img).toBeTruthy();
+ expect(img?.getAttribute("src")).toBe(att.url);
+ expect(img?.getAttribute("alt")).toBe("shot.png");
+ expect(screen.getByTitle("View")).toBeTruthy();
+ expect(screen.getByTitle("Download")).toBeTruthy();
+ expect(screen.getByTitle("Copy link")).toBeTruthy();
+ // Trash only shows in editable mode.
+ expect(screen.queryByTitle("Delete")).toBeNull();
+ });
+
+ it("editable image shows Trash button and wires onDelete", () => {
+ const att = makeRecord();
+ const onDelete = vi.fn();
+ renderWithQuery(
+ <Attachment
+ attachment={{ kind: "record", attachment: att }}
+ editable
+ onDelete={onDelete}
+ />,
+ );
+ const trash = screen.getByTitle("Delete");
+ fireEvent.click(trash);
+ expect(onDelete).toHaveBeenCalled();
+ });
+
+ it("url-only image resolves to a record via context and uses its id for download", () => {
+ const att = makeRecord({
+ filename: "from-resolver.png",
+ url: "https://cdn.example.test/from-resolver.png",
+ });
+ resolverState.attachments = [att];
+ renderWithQuery(
+ <Attachment
+ attachment={{
+ kind: "url",
+ url: att.url,
+ filename: "from-resolver.png",
+ }}
+ />,
+ );
+ const img = document.querySelector("img");
+ expect(img?.getAttribute("src")).toBe(att.url);
+ fireEvent.click(screen.getByTitle("Download"));
+ expect(downloadMock).toHaveBeenCalledWith("att-1");
+ });
+
+ it("forceKind=image renders as image even when filename is empty (markdown ![](url) regression)", () => {
+ renderWithQuery(
+ <Attachment
+ attachment={{
+ kind: "url",
+ url: "https://external.example/no-ext-here",
+ filename: "",
+ forceKind: "image",
+ }}
+ />,
+ );
+ // Without forceKind the empty filename would fall through to AttachmentCard.
+ // With forceKind="image" it must render as an <img>.
+ expect(document.querySelector("img")).toBeTruthy();
+ expect(screen.queryByText("Uploading")).toBeNull();
+ });
+
+ it("external image (no resolver match) renders <img> and falls back to openByUrl on Download", () => {
+ renderWithQuery(
+ <Attachment
+ attachment={{
+ kind: "url",
+ url: "https://external.example/foo.png",
+ filename: "foo.png",
+ }}
+ />,
+ );
+ const img = document.querySelector("img");
+ expect(img?.getAttribute("src")).toBe("https://external.example/foo.png");
+ fireEvent.click(screen.getByTitle("Download"));
+ expect(openByUrlMock).toHaveBeenCalledWith("https://external.example/foo.png");
+ expect(downloadMock).not.toHaveBeenCalled();
+ });
+
+ it("uploading image renders no toolbar (loader state)", () => {
+ renderWithQuery(
+ <Attachment
+ attachment={{
+ kind: "url",
+ url: "blob://local",
+ filename: "in-flight.png",
+ uploading: true,
+ }}
+ />,
+ );
+ expect(screen.queryByTitle("View")).toBeNull();
+ expect(screen.queryByTitle("Download")).toBeNull();
+ });
+});
+
+describe("Attachment — html dispatch", () => {
+ it("record html with attachmentId renders HtmlAttachmentPreview (no file-card chrome)", () => {
+ getAttachmentTextContentMock.mockResolvedValueOnce({
+ text: "<p>chart</p>",
+ originalContentType: "text/html",
+ });
+ const att = makeRecord({
+ filename: "report.html",
+ content_type: "text/html",
+ url: "https://cdn.example.test/report.html",
+ });
+ renderWithQuery(<Attachment attachment={{ kind: "record", attachment: att }} />);
+ // HtmlAttachmentPreview hides the filename row.
+ expect(screen.queryByText("report.html")).toBeNull();
+ expect(screen.getByTitle("Preview")).toBeTruthy();
+ expect(screen.getByTitle("Download")).toBeTruthy();
+ });
+
+ it("url-only html (no resolver match) falls back to AttachmentCard chrome", () => {
+ renderWithQuery(
+ <Attachment
+ attachment={{
+ kind: "url",
+ url: "https://external.example/report.html",
+ filename: "report.html",
+ contentType: "text/html",
+ }}
+ />,
+ );
+ // Without an attachment id the /content proxy is unreachable, so we
+ // show the chrome instead of the iframe.
+ expect(screen.getByText("report.html")).toBeTruthy();
+ expect(document.querySelector("iframe")).toBeNull();
+ });
+});
+
+describe("Attachment — file-card dispatch", () => {
+ it("record pdf renders the file-card chrome (filename + Preview/Download)", () => {
+ const att = makeRecord({
+ filename: "manual.pdf",
+ content_type: "application/pdf",
+ });
+ renderWithQuery(<Attachment attachment={{ kind: "record", attachment: att }} />);
+ expect(screen.getByText("manual.pdf")).toBeTruthy();
+ expect(document.querySelector("iframe")).toBeNull();
+ expect(document.querySelector("img")).toBeNull();
+ });
+
+ it("uploading file-card surfaces the uploading template, no Preview/Download", () => {
+ renderWithQuery(
+ <Attachment
+ attachment={{
+ kind: "url",
+ url: "blob://local",
+ filename: "in-flight.zip",
+ uploading: true,
+ }}
+ />,
+ );
+ expect(screen.getByText("Uploading {{filename}}")).toBeTruthy();
+ // Preview/Download chrome is hidden while uploading.
+ expect(screen.queryByTitle("Preview")).toBeNull();
+ expect(screen.queryByTitle("Download")).toBeNull();
+ });
+});
diff --git a/packages/views/editor/attachment.tsx b/packages/views/editor/attachment.tsx
new file mode 100644
index 0000000000..48ab4b59f9
--- /dev/null
+++ b/packages/views/editor/attachment.tsx
@@ -0,0 +1,342 @@
+"use client";
+
+/**
+ * Attachment — single unified renderer for every attachment surface.
+ *
+ * Takes one attachment-shaped input (a full record, a URL-only reference, or
+ * an in-flight upload) and dispatches by PreviewKind:
+ *
+ * - image → ImageAttachmentView (figure + hover toolbar + lightbox via
+ * the shared AttachmentPreviewModal)
+ * - html → HtmlAttachmentPreview (inline iframe + hover toolbar)
+ * - others → AttachmentCard (icon + filename + Eye/Download row)
+ *
+ * Call sites:
+ * - extensions/file-card.tsx FileCardView (Tiptap NodeView)
+ * - extensions/image-view.tsx ImageView (Tiptap NodeView)
+ * - readonly-content.tsx (markdown img + fileCard div renderers)
+ * - issues/components/comment-card.tsx AttachmentList (standalone fallback)
+ * - common/markdown.tsx (chat / skill viewer Markdown wrapper)
+ *
+ * The component owns its own preview modal and download dispatcher — callers
+ * just pass `attachment` and (for editor surfaces) optional editor chrome
+ * hints (selected, editable, onDelete).
+ */
+
+import {
+ Download,
+ Link as LinkIcon,
+ Maximize2,
+ Trash2,
+} from "lucide-react";
+import { toast } from "sonner";
+import { cn } from "@multica/ui/lib/utils";
+import type { Attachment as AttachmentRecord } from "@multica/core/types";
+import { useT } from "../i18n";
+import { useAttachmentDownloadResolver } from "./attachment-download-context";
+import { useAttachmentPreview } from "./attachment-preview-modal";
+import { useDownloadAttachment } from "./use-download-attachment";
+import { AttachmentCard } from "./attachment-card";
+import { HtmlAttachmentPreview } from "./html-attachment-preview";
+import { getPreviewKind, type PreviewKind } from "./utils/preview";
+
+// ---------------------------------------------------------------------------
+// Public API
+// ---------------------------------------------------------------------------
+
+export type AttachmentInput =
+ // Server response in hand — full record. Used by AttachmentList and any
+ // caller iterating a server-returned attachments[] array.
+ | { kind: "record"; attachment: AttachmentRecord }
+ // Markdown / Tiptap inline: only a URL + filename. Resolves to a full
+ // record via the surrounding AttachmentDownloadProvider when available;
+ // otherwise renders in URL-only mode (media types still preview from URL,
+ // text types fall back to a download CTA).
+ | {
+ kind: "url";
+ url: string;
+ filename: string;
+ contentType?: string;
+ /** Editor in-flight state. Renders a loader placeholder. */
+ uploading?: boolean;
+ /**
+ * Structural hint from the call site: "this slot is definitionally an
+ * image / file / ...". Bypasses `getPreviewKind` autodetect, which
+ * needs a filename or content-type and falls back to the file-card
+ * chrome when neither is available. Required for callers that KNOW
+ * the kind from context (markdown `![]()` is always an image; Tiptap
+ * image NodeView is always an image) but receive only a URL with an
+ * empty `alt`/`filename`.
+ */
+ forceKind?: PreviewKind;
+ };
+
+export interface AttachmentProps {
+ attachment: AttachmentInput;
+ /** Editor hint — when true, the image toolbar exposes Trash. */
+ editable?: boolean;
+ /** Editor hint — applies the "selected" visual to the image figure. */
+ selected?: boolean;
+ /** Editor hint — wired to Tiptap deleteNode(). */
+ onDelete?: () => void;
+ className?: string;
+}
+
+interface Normalized {
+ filename: string;
+ contentType: string;
+ url: string;
+ attachmentId?: string;
+ record?: AttachmentRecord;
+ uploading: boolean;
+}
+
+function normalize(
+ input: AttachmentInput,
+ resolve: (url: string) => AttachmentRecord | undefined,
+): Normalized {
+ if (input.kind === "record") {
+ return {
+ filename: input.attachment.filename,
+ contentType: input.attachment.content_type,
+ url: input.attachment.url,
+ attachmentId: input.attachment.id,
+ record: input.attachment,
+ uploading: false,
+ };
+ }
+ const record = input.url ? resolve(input.url) : undefined;
+ return {
+ filename: input.filename || record?.filename || "",
+ contentType: input.contentType || record?.content_type || "",
+ url: input.url,
+ attachmentId: record?.id,
+ record,
+ uploading: !!input.uploading,
+ };
+}
+
+// ---------------------------------------------------------------------------
+// Dispatcher
+// ---------------------------------------------------------------------------
+
+export function Attachment({
+ attachment,
+ editable,
+ selected,
+ onDelete,
+ className,
+}: AttachmentProps) {
+ const { resolveAttachment, openByUrl } = useAttachmentDownloadResolver();
+ const download = useDownloadAttachment();
+ const preview = useAttachmentPreview();
+
+ const state = normalize(attachment, resolveAttachment);
+ const forceKind =
+ attachment.kind === "url" ? attachment.forceKind : undefined;
+ const kind =
+ forceKind ??
+ (state.filename || state.contentType
+ ? getPreviewKind(state.contentType, state.filename)
+ : null);
+
+ const openPreview = () => {
+ if (state.record) {
+ preview.tryOpen({ kind: "full", attachment: state.record });
+ return;
+ }
+ if (state.url) {
+ preview.tryOpen({
+ kind: "url",
+ url: state.url,
+ filename: state.filename,
+ });
+ }
+ };
+
+ const handleDownload = () => {
+ if (state.attachmentId) {
+ download(state.attachmentId);
+ return;
+ }
+ if (state.url) openByUrl(state.url);
+ };
+
+ if (kind === "image") {
+ return (
+ <>
+ <ImageAttachmentView
+ src={state.url}
+ alt={state.filename}
+ uploading={state.uploading}
+ editable={editable}
+ selected={selected}
+ onView={openPreview}
+ onDownload={handleDownload}
+ onDelete={onDelete}
+ className={className}
+ />
+ {preview.modal}
+ </>
+ );
+ }
+
+ if (kind === "html" && state.attachmentId && !state.uploading) {
+ return (
+ <>
+ <HtmlAttachmentPreview
+ attachmentId={state.attachmentId}
+ filename={state.filename}
+ onPreview={openPreview}
+ onDownload={handleDownload}
+ />
+ {preview.modal}
+ </>
+ );
+ }
+
+ return (
+ <>
+ <AttachmentCard
+ filename={state.filename}
+ contentType={state.contentType}
+ attachmentId={state.attachmentId}
+ href={state.url || undefined}
+ uploading={state.uploading}
+ onPreview={openPreview}
+ onDownload={handleDownload}
+ />
+ {preview.modal}
+ </>
+ );
+}
+
+// ---------------------------------------------------------------------------
+// ImageAttachmentView — inline image with hover toolbar
+// ---------------------------------------------------------------------------
+//
+// Self-contained Tailwind: works inside the editor surface (where the legacy
+// `.rich-text-editor .image-figure` CSS in content-editor.css continues to
+// apply for backward compatibility) AND in standalone surfaces (chat
+// messages, comment-card AttachmentList) that don't carry that scope.
+
+interface ImageAttachmentViewProps {
+ src: string;
+ alt: string;
+ uploading: boolean;
+ editable?: boolean;
+ selected?: boolean;
+ onView: () => void;
+ onDownload: () => void;
+ onDelete?: () => void;
+ className?: string;
+}
+
+function ImageAttachmentView({
+ src,
+ alt,
+ uploading,
+ editable,
+ selected,
+ onView,
+ onDownload,
+ onDelete,
+ className,
+}: ImageAttachmentViewProps) {
+ const { t } = useT("editor");
+
+ const handleCopyLink = async () => {
+ try {
+ await navigator.clipboard.writeText(src);
+ toast.success(t(($) => $.image.link_copied));
+ } catch {
+ toast.error(t(($) => $.image.copy_link_failed));
+ }
+ };
+
+ // Click on figure opens the preview only in non-editor surfaces — inside
+ // the editor we let ProseMirror own the click for selection / cursor
+ // placement and route preview through the explicit Maximize button.
+ const figureOnClick = !editable && !uploading ? onView : undefined;
+
+ return (
+ <span
+ className={cn(
+ "image-node group/image relative inline-block max-w-full",
+ className,
+ )}
+ >
+ <span
+ className={cn(
+ "image-figure relative inline-block max-w-full rounded-md transition-shadow",
+ selected && editable && "image-selected ring-2 ring-primary",
+ !editable && !uploading && "cursor-zoom-in",
+ )}
+ onClick={figureOnClick}
+ >
+ {src ? (
+ <img
+ src={src}
+ alt={alt}
+ className={cn(
+ "image-content block max-w-full rounded-md",
+ uploading && "image-uploading opacity-60",
+ )}
+ draggable={false}
+ />
+ ) : (
+ // Defensive: an image input without a URL is degenerate, but
+ // emitting nothing leaves no anchor for the toolbar. Render a
+ // small placeholder so the surface is still recognizable.
+ <span className="block h-20 w-32 rounded-md bg-muted" />
+ )}
+ {!uploading && src && (
+ <span
+ className="image-toolbar absolute right-2 top-2 flex items-center gap-0.5 rounded-md border border-border bg-background/95 p-0.5 opacity-0 shadow-sm transition-opacity group-hover/image:opacity-100"
+ onMouseDown={(e) => e.stopPropagation()}
+ onClick={(e) => e.stopPropagation()}
+ >
+ <button
+ type="button"
+ className="flex h-6 w-6 items-center justify-center rounded text-muted-foreground transition-colors hover:bg-muted hover:text-foreground"
+ title={t(($) => $.image.view)}
+ aria-label={t(($) => $.image.view)}
+ onClick={onView}
+ >
+ <Maximize2 className="size-3.5" />
+ </button>
+ <button
+ type="button"
+ className="flex h-6 w-6 items-center justify-center rounded text-muted-foreground transition-colors hover:bg-muted hover:text-foreground"
+ title={t(($) => $.image.download)}
+ aria-label={t(($) => $.image.download)}
+ onClick={onDownload}
+ >
+ <Download className="size-3.5" />
+ </button>
+ <button
+ type="button"
+ className="flex h-6 w-6 items-center justify-center rounded text-muted-foreground transition-colors hover:bg-muted hover:text-foreground"
+ title={t(($) => $.image.copy_link)}
+ aria-label={t(($) => $.image.copy_link)}
+ onClick={handleCopyLink}
+ >
+ <LinkIcon className="size-3.5" />
+ </button>
+ {editable && onDelete && (
+ <button
+ type="button"
+ className="flex h-6 w-6 items-center justify-center rounded text-muted-foreground transition-colors hover:bg-muted hover:text-foreground"
+ title={t(($) => $.image.delete)}
+ aria-label={t(($) => $.image.delete)}
+ onClick={onDelete}
+ >
+ <Trash2 className="size-3.5" />
+ </button>
+ )}
+ </span>
+ )}
+ </span>
+ </span>
+ );
+}
diff --git a/packages/views/editor/extensions/file-card.tsx b/packages/views/editor/extensions/file-card.tsx
index fe7285a5e9..e65b580bf1 100644
--- a/packages/views/editor/extensions/file-card.tsx
+++ b/packages/views/editor/extensions/file-card.tsx
@@ -18,9 +18,7 @@ import { Node, mergeAttributes } from "@tiptap/core";
import { ReactNodeViewRenderer, NodeViewWrapper } from "@tiptap/react";
import type { NodeViewProps } from "@tiptap/react";
import { FILE_CARD_URL_PATTERN } from "@multica/ui/markdown";
-import { useAttachmentDownloadResolver } from "../attachment-download-context";
-import { useAttachmentPreview } from "../attachment-preview-modal";
-import { AttachmentBlock } from "../attachment-block";
+import { Attachment } from "../attachment";
const FILE_CARD_MARKDOWN_RE = new RegExp(
`^!file\\[([^\\]]*)\\]\\((${FILE_CARD_URL_PATTERN.source})\\)`,
@@ -28,45 +26,21 @@ const FILE_CARD_MARKDOWN_RE = new RegExp(
// ---------------------------------------------------------------------------
-// React NodeView
+// React NodeView — thin wrapper, all rendering lives in <Attachment>
// ---------------------------------------------------------------------------
export function FileCardView({ node }: NodeViewProps) {
const href = (node.attrs.href as string) || "";
const filename = (node.attrs.filename as string) || "";
const uploading = node.attrs.uploading as boolean;
- const { openByUrl, resolveAttachment } = useAttachmentDownloadResolver();
- const preview = useAttachmentPreview();
-
- // Preview gate widens to "anything that can be downloaded AND whose
- // filename is a previewable type". Media kinds remain previewable when the
- // attachment record isn't reachable (e.g. URL was copy-pasted across
- // comments). Text kinds (markdown / html / text) need the id because the
- // preview proxy is ID-keyed.
- const attachment = href ? resolveAttachment(href) : undefined;
-
- const openPreview = () => {
- if (attachment) {
- preview.tryOpen({ kind: "full", attachment });
- } else if (href) {
- preview.tryOpen({ kind: "url", url: href, filename });
- }
- };
return (
<NodeViewWrapper as="div" className="file-card-node" data-type="fileCard">
<div contentEditable={false}>
- <AttachmentBlock
- filename={filename}
- contentType={attachment?.content_type ?? ""}
- attachmentId={attachment?.id}
- href={href}
- uploading={uploading}
- onPreview={openPreview}
- onDownload={() => openByUrl(href)}
+ <Attachment
+ attachment={{ kind: "url", url: href, filename, uploading }}
/>
</div>
- {preview.modal}
</NodeViewWrapper>
);
}
diff --git a/packages/views/editor/extensions/image-view.tsx b/packages/views/editor/extensions/image-view.tsx
index 4ed588218c..3ee38ad9b1 100644
--- a/packages/views/editor/extensions/image-view.tsx
+++ b/packages/views/editor/extensions/image-view.tsx
@@ -1,148 +1,39 @@
"use client";
-import { useEffect, useState } from "react";
-import { createPortal } from "react-dom";
+/**
+ * ImageView — Tiptap NodeView for the image node.
+ *
+ * Thin wrapper around the unified `<Attachment>` dispatcher. All rendering
+ * (figure, hover toolbar, lightbox/preview) lives there. The NodeView only
+ * forwards Tiptap's editor-context hints (editable, selected, deleteNode).
+ */
+
import { NodeViewWrapper } from "@tiptap/react";
import type { NodeViewProps } from "@tiptap/react";
-import {
- Maximize2,
- Download,
- Link as LinkIcon,
- Trash2,
-} from "lucide-react";
-import { toast } from "sonner";
-import { cn } from "@multica/ui/lib/utils";
-import { useT } from "../../i18n";
-import { useAttachmentDownloadResolver } from "../attachment-download-context";
-
-// ---------------------------------------------------------------------------
-// Lightbox — full-screen image preview (ESC or click backdrop to close)
-// ---------------------------------------------------------------------------
-
-function ImageLightbox({
- src,
- alt,
- onClose,
-}: {
- src: string;
- alt: string;
- onClose: () => void;
-}) {
- useEffect(() => {
- const handler = (e: KeyboardEvent) => {
- if (e.key === "Escape") onClose();
- };
- document.addEventListener("keydown", handler);
- return () => document.removeEventListener("keydown", handler);
- }, [onClose]);
-
- return createPortal(
- <div
- className="fixed inset-0 z-50 flex items-center justify-center bg-black/80 cursor-zoom-out"
- onClick={onClose}
- >
- <img
- src={src}
- alt={alt}
- className="max-h-[90vh] max-w-[90vw] rounded-lg object-contain"
- onClick={(e) => e.stopPropagation()}
- />
- </div>,
- document.body,
- );
-}
-
-// ---------------------------------------------------------------------------
-// Image NodeView — renders img with hover toolbar + lightbox
-// ---------------------------------------------------------------------------
+import { Attachment } from "../attachment";
function ImageView({ node, editor, selected, deleteNode }: NodeViewProps) {
- const { t } = useT("editor");
- const src = node.attrs.src as string;
+ const src = (node.attrs.src as string) || "";
const alt = (node.attrs.alt as string) || "";
- const title = node.attrs.title as string | undefined;
const uploading = node.attrs.uploading as boolean;
- const { openByUrl } = useAttachmentDownloadResolver();
-
- const [lightbox, setLightbox] = useState(false);
- const isEditable = editor.isEditable;
-
- const handleView = () => setLightbox(true);
-
- const handleDownload = () => {
- // Cross-origin CDN images can't be fetched as blob (CORS),
- // and <a download> is ignored for cross-origin URLs.
- // Re-sign through the provider when the src maps to a known
- // attachment; otherwise just open externally.
- openByUrl(src);
- };
-
- const handleCopyLink = async () => {
- try {
- await navigator.clipboard.writeText(src);
- toast.success(t(($) => $.image.link_copied));
- } catch {
- toast.error(t(($) => $.image.copy_link_failed));
- }
- };
return (
<NodeViewWrapper className="image-node">
- <figure
- className={cn(
- "image-figure",
- selected && isEditable && "image-selected",
- )}
- contentEditable={false}
- onClick={!isEditable && !uploading ? handleView : undefined}
- >
- <img
- src={src}
- alt={alt}
- title={title || undefined}
- className={cn("image-content", uploading && "image-uploading")}
- draggable={false}
- />
- {!uploading && (
- <div
- className="image-toolbar"
- onMouseDown={(e) => e.stopPropagation()}
- onClick={(e) => e.stopPropagation()}
- >
- <button type="button" onClick={handleView} title={t(($) => $.image.view)}>
- <Maximize2 className="size-3.5" />
- </button>
- <button type="button" onClick={handleDownload} title={t(($) => $.image.download)}>
- <Download className="size-3.5" />
- </button>
- <button
- type="button"
- onClick={handleCopyLink}
- title={t(($) => $.image.copy_link)}
- >
- <LinkIcon className="size-3.5" />
- </button>
- {isEditable && (
- <button
- type="button"
- onClick={() => deleteNode()}
- title={t(($) => $.image.delete)}
- >
- <Trash2 className="size-3.5" />
- </button>
- )}
- </div>
- )}
- </figure>
- {lightbox && (
- <ImageLightbox
- src={src}
- alt={alt}
- onClose={() => setLightbox(false)}
- />
- )}
+ <Attachment
+ attachment={{
+ kind: "url",
+ url: src,
+ filename: alt,
+ uploading,
+ // Tiptap image node is structurally an image regardless of alt.
+ forceKind: "image",
+ }}
+ editable={editor.isEditable}
+ selected={selected}
+ onDelete={() => deleteNode()}
+ />
</NodeViewWrapper>
);
}
-export { ImageView, ImageLightbox };
+export { ImageView };
diff --git a/packages/views/editor/html-attachment-preview.tsx b/packages/views/editor/html-attachment-preview.tsx
index 088407b310..449f4c34ad 100644
--- a/packages/views/editor/html-attachment-preview.tsx
+++ b/packages/views/editor/html-attachment-preview.tsx
@@ -15,9 +15,9 @@
* `openInNewTab` to add an app tab; web falls back to `window.open` against
* the shareable URL.
*
- * Mounted by AttachmentBlock when the attachment is HTML and the caller can
- * supply an `attachmentId` (the /content proxy is ID-keyed). For other kinds,
- * AttachmentBlock falls back to the shared AttachmentCard.
+ * Mounted by the unified `<Attachment>` dispatcher when the attachment is
+ * HTML and an `attachmentId` is resolvable (the /content proxy is ID-keyed).
+ * For other kinds, `<Attachment>` falls back to the shared AttachmentCard.
*
* Failure mode (413 / 415 / transport): we do not unmount the figure or fall
* back to AttachmentCard chrome — standalone attachment lists filter URLs
diff --git a/packages/views/editor/index.ts b/packages/views/editor/index.ts
index 0a2971a7a2..6003909a67 100644
--- a/packages/views/editor/index.ts
+++ b/packages/views/editor/index.ts
@@ -22,5 +22,5 @@ export {
export type { AttachmentPreviewHandle } from "./attachment-preview-modal";
export { AttachmentCard } from "./attachment-card";
export type { AttachmentCardProps } from "./attachment-card";
-export { AttachmentBlock } from "./attachment-block";
-export type { AttachmentBlockProps } from "./attachment-block";
+export { Attachment } from "./attachment";
+export type { AttachmentInput, AttachmentProps } from "./attachment";
diff --git a/packages/views/editor/readonly-content.tsx b/packages/views/editor/readonly-content.tsx
index b7e89880a3..7332070e26 100644
--- a/packages/views/editor/readonly-content.tsx
+++ b/packages/views/editor/readonly-content.tsx
@@ -16,7 +16,7 @@
* - Rendering mentions with the same IssueMentionCard component and .mention class
*/
-import { isValidElement, memo, useCallback, useMemo, useRef, useState } from "react";
+import { isValidElement, memo, useMemo, useRef } from "react";
import ReactMarkdown, {
defaultUrlTransform,
type Components,
@@ -29,25 +29,19 @@ import rehypeRaw from "rehype-raw";
import rehypeSanitize, { defaultSchema } from "rehype-sanitize";
import { createLowlight, common } from "lowlight";
import { toHtml } from "hast-util-to-html";
-import { Maximize2, Download, Link as LinkIcon } from "lucide-react";
-import { toast } from "sonner";
import { cn } from "@multica/ui/lib/utils";
import { useWorkspacePaths, useWorkspaceSlug } from "@multica/core/paths";
import type { Attachment } from "@multica/core/types";
import { useNavigation } from "../navigation";
-import { useT } from "../i18n";
-import { openExternal } from "../platform";
import { IssueMentionCard } from "../issues/components/issue-mention-card";
-import { ImageLightbox } from "./extensions/image-view";
import { useLinkHover, LinkHoverCard } from "./link-hover-card";
import { openLink, isMentionHref } from "./utils/link-handler";
import { isAllowedFileCardHref } from "@multica/ui/markdown";
import { preprocessMarkdown } from "./utils/preprocess";
import { MermaidDiagram } from "./mermaid-diagram";
import { HtmlBlockPreview } from "./html-block-preview";
-import { useDownloadAttachment } from "./use-download-attachment";
-import { useAttachmentPreview, type PreviewSource } from "./attachment-preview-modal";
-import { AttachmentBlock } from "./attachment-block";
+import { AttachmentDownloadProvider } from "./attachment-download-context";
+import { Attachment as AttachmentRenderer } from "./attachment";
import "katex/dist/katex.min.css";
import "./content-editor.css";
@@ -173,136 +167,26 @@ function ReadonlyLink({
);
}
-// Image renderer with a download button that prefers fresh-signed URLs.
-// Lifted out of the components map so it can call hooks; receives the
-// attachment lookup as props so the components map can stay a pure
-// data-build inside `ReadonlyContent`'s `useMemo`.
-function ReadonlyImage({
- src,
- alt,
- resolveAttachmentId,
- onDownload,
-}: {
- src?: string;
- alt?: string;
- resolveAttachmentId: (url: string) => string | undefined;
- onDownload: (attachmentId: string) => void;
-}) {
- const { t } = useT("editor");
- const [lightbox, setLightbox] = useState(false);
- const imgSrc = typeof src === "string" ? src : "";
- const imgAlt = alt ?? "";
-
- const handleView = () => setLightbox(true);
- const handleDownload = () => {
- const id = imgSrc ? resolveAttachmentId(imgSrc) : undefined;
- if (id) {
- onDownload(id);
- return;
- }
- // External image — no attachment record to re-sign through. Falling back
- // to `openExternal` keeps us off `window.open(...)` (which Electron's
- // setWindowOpenHandler would route through openExternalSafely anyway,
- // but only after rejecting non-http schemes loudly).
- if (imgSrc) openExternal(imgSrc);
- };
- const handleCopyLink = async () => {
- try {
- await navigator.clipboard.writeText(imgSrc);
- toast.success(t(($) => $.image.link_copied));
- } catch {
- toast.error(t(($) => $.image.copy_link_failed));
- }
- };
-
- return (
- <span className="image-node">
- <span className="image-figure" onClick={handleView}>
- <img src={imgSrc} alt={imgAlt} className="image-content" draggable={false} />
- <span
- className="image-toolbar"
- onMouseDown={(e) => e.stopPropagation()}
- onClick={(e) => e.stopPropagation()}
- >
- <button type="button" onClick={handleView} title={t(($) => $.image.view)}>
- <Maximize2 className="size-3.5" />
- </button>
- <button type="button" onClick={handleDownload} title={t(($) => $.image.download)}>
- <Download className="size-3.5" />
- </button>
- <button type="button" onClick={handleCopyLink} title={t(($) => $.image.copy_link)}>
- <LinkIcon className="size-3.5" />
- </button>
- </span>
- </span>
- {lightbox && (
- <ImageLightbox src={imgSrc} alt={imgAlt} onClose={() => setLightbox(false)} />
- )}
- </span>
- );
-}
-
-// Inline file card — wraps the shared AttachmentCard with the same
-// download semantics as the standalone attachment list: fresh-sign through
-// `useDownloadAttachment` when the href matches a known attachment,
-// otherwise hand the raw URL to the platform's external opener.
-function ReadonlyFileCard({
- href,
- filename,
- resolveAttachment,
- onDownload,
- onPreview,
-}: {
- href: string;
- filename: string;
- resolveAttachment: (url: string) => Attachment | undefined;
- onDownload: (attachmentId: string) => void;
- onPreview: (source: PreviewSource) => boolean;
-}) {
- const attachment = href ? resolveAttachment(href) : undefined;
- const handleDownloadClick = () => {
- if (attachment) {
- onDownload(attachment.id);
- return;
- }
- openExternal(href);
- };
- const handlePreviewClick = () => {
- if (attachment) {
- onPreview({ kind: "full", attachment });
- } else if (href) {
- onPreview({ kind: "url", url: href, filename });
- }
- };
- return (
- <AttachmentBlock
- filename={filename}
- contentType={attachment?.content_type ?? ""}
- attachmentId={attachment?.id}
- href={href}
- onPreview={handlePreviewClick}
- onDownload={handleDownloadClick}
- />
- );
-}
-
-function buildComponents(
- resolveAttachmentId: (url: string) => string | undefined,
- resolveAttachment: (url: string) => Attachment | undefined,
- onDownload: (attachmentId: string) => void,
- onPreview: (source: PreviewSource) => boolean,
-): Partial<Components> {
+function buildComponents(): Partial<Components> {
return {
// Links — route mention:// to mention components, others show preview card
a: ReadonlyLink,
- // Images — centered with toolbar + lightbox (matches Tiptap ImageView NodeView)
+ // Images — unified through <Attachment>. The resolver context provided
+ // by AttachmentDownloadProvider (mounted in ReadonlyContent below) turns
+ // a CDN URL into a full record when possible; external URLs render as
+ // plain images with lightbox-via-preview-modal. forceKind is mandatory
+ // here because markdown `![]()` carries no content-type and alt is
+ // commonly empty or descriptive — without it images fall through to
+ // the file-card chrome.
img: ({ src, alt }) => (
- <ReadonlyImage
- src={typeof src === "string" ? src : undefined}
- alt={alt ?? undefined}
- resolveAttachmentId={resolveAttachmentId}
- onDownload={onDownload}
+ <AttachmentRenderer
+ attachment={{
+ kind: "url",
+ url: typeof src === "string" ? src : "",
+ filename: alt ?? "",
+ forceKind: "image",
+ }}
/>
),
@@ -314,12 +198,8 @@ function buildComponents(
const href = isAllowedFileCardHref(rawHref) ? rawHref : "";
const filename = (node?.properties?.dataFilename as string) || "";
return (
- <ReadonlyFileCard
- href={href}
- filename={filename}
- resolveAttachment={resolveAttachment}
- onDownload={onDownload}
- onPreview={onPreview}
+ <AttachmentRenderer
+ attachment={{ kind: "url", url: href, filename }}
/>
);
}
@@ -437,43 +317,24 @@ export const ReadonlyContent = memo(function ReadonlyContent({
const processed = useMemo(() => preprocessMarkdown(content), [content]);
const wrapperRef = useRef<HTMLDivElement>(null);
const hover = useLinkHover(wrapperRef);
- const download = useDownloadAttachment();
-
- const resolveAttachmentId = useCallback(
- (url: string): string | undefined => {
- if (!url || !attachments?.length) return undefined;
- return attachments.find((a) => a.url === url)?.id;
- },
- [attachments],
- );
-
- const resolveAttachment = useCallback(
- (url: string): Attachment | undefined => {
- if (!url || !attachments?.length) return undefined;
- return attachments.find((a) => a.url === url);
- },
- [attachments],
- );
- const preview = useAttachmentPreview();
-
- const components = useMemo(
- () => buildComponents(resolveAttachmentId, resolveAttachment, download, preview.tryOpen),
- [resolveAttachmentId, resolveAttachment, download, preview.tryOpen],
- );
+ // Components map is now static — all attachment-aware logic lives in
+ // <Attachment>, which reads the surrounding AttachmentDownloadProvider.
+ const components = useMemo(() => buildComponents(), []);
return (
- <div ref={wrapperRef} className={cn("rich-text-editor readonly text-sm", className)}>
- <ReactMarkdown
- remarkPlugins={[remarkMath, remarkBreaks, [remarkGfm, { singleTilde: false }]]}
- rehypePlugins={[rehypeRaw, [rehypeSanitize, sanitizeSchema], rehypeKatex]}
- urlTransform={urlTransform}
- components={components}
- >
- {processed}
- </ReactMarkdown>
- <LinkHoverCard {...hover} />
- {preview.modal}
- </div>
+ <AttachmentDownloadProvider attachments={attachments}>
+ <div ref={wrapperRef} className={cn("rich-text-editor readonly text-sm", className)}>
+ <ReactMarkdown
+ remarkPlugins={[remarkMath, remarkBreaks, [remarkGfm, { singleTilde: false }]]}
+ rehypePlugins={[rehypeRaw, [rehypeSanitize, sanitizeSchema], rehypeKatex]}
+ urlTransform={urlTransform}
+ components={components}
+ >
+ {processed}
+ </ReactMarkdown>
+ <LinkHoverCard {...hover} />
+ </div>
+ </AttachmentDownloadProvider>
);
});
diff --git a/packages/views/editor/utils/preview.ts b/packages/views/editor/utils/preview.ts
index 1fb1f404c6..68aeaf9890 100644
--- a/packages/views/editor/utils/preview.ts
+++ b/packages/views/editor/utils/preview.ts
@@ -11,6 +11,7 @@
*/
export type PreviewKind =
+ | "image"
| "pdf"
| "video"
| "audio"
@@ -122,6 +123,9 @@ const VIDEO_EXTS = new Set<string>([
const AUDIO_EXTS = new Set<string>([
"mp3", "wav", "m4a", "ogg", "oga", "flac", "aac", "opus",
]);
+const IMAGE_EXTS = new Set<string>([
+ "png", "jpg", "jpeg", "gif", "webp", "avif", "bmp", "ico", "svg",
+]);
function extOf(filename: string): string {
const base = filename.toLowerCase().split(/[\\/]/).pop() ?? "";
@@ -164,6 +168,11 @@ export function getPreviewKind(
if (ct.startsWith("video/") || (ext && VIDEO_EXTS.has(ext))) return "video";
if (ct.startsWith("audio/") || (ext && AUDIO_EXTS.has(ext))) return "audio";
+ // Image — must come BEFORE the html/text branches because svg is
+ // text-like (XML), and image/* content-types include text/svg variants
+ // that isTextLike would otherwise catch.
+ if (ct.startsWith("image/") || (ext && IMAGE_EXTS.has(ext))) return "image";
+
// Markdown — covers both the well-typed case and the common
// server-side sniffer fallback (text/plain for .md).
if (ct === "text/markdown" || ext === "md" || ext === "markdown") {
diff --git a/packages/views/issues/components/comment-card.tsx b/packages/views/issues/components/comment-card.tsx
index 47f2a69055..d345e63674 100644
--- a/packages/views/issues/components/comment-card.tsx
+++ b/packages/views/issues/components/comment-card.tsx
@@ -30,7 +30,7 @@ import { QuickEmojiPicker } from "@multica/ui/components/common/quick-emoji-pick
import { cn } from "@multica/ui/lib/utils";
import { useActorName } from "@multica/core/workspace/hooks";
import { timeAgo } from "@multica/core/utils";
-import { ContentEditor, type ContentEditorRef, copyMarkdown, ReadonlyContent, useFileDropZone, FileDropOverlay, useDownloadAttachment, useAttachmentPreview, AttachmentBlock } from "../../editor";
+import { ContentEditor, type ContentEditorRef, copyMarkdown, ReadonlyContent, useFileDropZone, FileDropOverlay, Attachment as AttachmentRenderer, AttachmentDownloadProvider } from "../../editor";
import { FileUploadButton } from "@multica/ui/components/common/file-upload-button";
import { useFileUpload } from "@multica/core/hooks/use-file-upload";
import { api } from "@multica/core/api";
@@ -122,8 +122,6 @@ function DeleteCommentDialog({
// ---------------------------------------------------------------------------
export function AttachmentList({ attachments, content, className }: { attachments?: Attachment[]; content?: string; className?: string }) {
- const download = useDownloadAttachment();
- const preview = useAttachmentPreview();
if (!attachments?.length) return null;
// Skip attachments whose URL is already referenced in the markdown content,
// and duplicates of the same file (same name/type/size) that are referenced.
@@ -147,20 +145,16 @@ export function AttachmentList({ attachments, content, className }: { attachment
if (!standalone.length) return null;
return (
- <div className={cn("flex flex-col gap-1", className)}>
- {standalone.map((a) => (
- <AttachmentBlock
- key={a.id}
- filename={a.filename}
- contentType={a.content_type}
- attachmentId={a.id}
- href={a.url}
- onPreview={() => preview.tryOpen({ kind: "full", attachment: a })}
- onDownload={() => download(a.id)}
- />
- ))}
- {preview.modal}
- </div>
+ <AttachmentDownloadProvider attachments={attachments}>
+ <div className={cn("flex flex-col gap-1", className)}>
+ {standalone.map((a) => (
+ <AttachmentRenderer
+ key={a.id}
+ attachment={{ kind: "record", attachment: a }}
+ />
+ ))}
+ </div>
+ </AttachmentDownloadProvider>
);
}