Skip to content

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

Go

MUL-7642: full-window attachment viewer that pages through every file (#8763)

Jiayuan Zhang1d94166dc2d3
diff --git a/packages/core/attachments/image-sequence.test.ts b/packages/core/attachments/image-sequence.test.ts
index 29e7110232..f13732f2f5 100644
--- a/packages/core/attachments/image-sequence.test.ts
+++ b/packages/core/attachments/image-sequence.test.ts
@@ -1,6 +1,7 @@
import { describe, expect, it } from "vitest";
import type { Attachment } from "../types/attachment";
import {
+ collectAttachmentSequence,
collectImageSequence,
indexOfImageKey,
isImageAttachment,
@@ -143,6 +144,7 @@ describe("collectImageSequence", () => {
url: "https://cdn/x.png",
filename: "shot",
attachment: undefined,
+ imageByConstruction: true,
},
]);
});
@@ -204,6 +206,101 @@ describe("collectImageSequence", () => {
});
});
+describe("collectAttachmentSequence", () => {
+ // The web / desktop rule: anything the viewer can open.
+ const previewable = ({ contentType, filename }: { contentType: string; filename: string }) =>
+ isImageAttachment(contentType, filename) ||
+ contentType === "application/pdf" ||
+ filename.endsWith(".md");
+
+ it("pages through every kind the rule accepts, in render order", () => {
+ const pdf = attachment({
+ id: UUID_A,
+ filename: "spec.pdf",
+ content_type: "application/pdf",
+ });
+ const image = attachment({ id: UUID_B });
+ const zip = attachment({
+ id: UUID_C,
+ filename: "bundle.zip",
+ content_type: "application/zip",
+ });
+
+ const sequence = collectAttachmentSequence(
+ [
+ {
+ content: `![shot](/api/attachments/${UUID_B}/download)`,
+ attachments: [image, pdf, zip],
+ },
+ ],
+ previewable,
+ );
+
+ expect(sequence.map((i) => i.key)).toEqual([UUID_B, UUID_A]);
+ expect(sequence.map((i) => i.imageByConstruction)).toEqual([true, false]);
+ });
+
+ it("asks the rule about file cards and says whether they resolved", () => {
+ const seen: Array<{ filename: string; hasRecord: boolean }> = [];
+ const notes = attachment({
+ id: UUID_A,
+ filename: "notes.md",
+ content_type: "text/markdown",
+ });
+
+ const sequence = collectAttachmentSequence(
+ [
+ {
+ content: [
+ `!file[notes.md](/api/attachments/${UUID_A}/download)`,
+ "!file[orphan.md](https://cdn/orphan.md)",
+ ].join("\n\n"),
+ attachments: [notes],
+ },
+ ],
+ (candidate) => {
+ seen.push({ filename: candidate.filename, hasRecord: candidate.hasRecord });
+ return candidate.hasRecord;
+ },
+ );
+
+ expect(seen).toEqual([
+ { filename: "notes.md", hasRecord: true },
+ { filename: "orphan.md", hasRecord: false },
+ ]);
+ expect(sequence.map((i) => i.key)).toEqual([UUID_A]);
+ });
+
+ it("resolves a non-standalone block's references without listing the rest", () => {
+ const inline = attachment({ id: UUID_A });
+ const elsewhere = attachment({ id: UUID_B, filename: "later.png" });
+ const sequence = collectAttachmentSequence(
+ [
+ {
+ content: `![](/api/attachments/${UUID_A}/download)`,
+ attachments: [inline, elsewhere],
+ standalone: false,
+ },
+ { attachments: [elsewhere] },
+ ],
+ previewable,
+ );
+ // `elsewhere` sits at its own block's position, not the first block's.
+ expect(sequence.map((i) => [i.key, i.attachment])).toEqual([
+ [UUID_A, inline],
+ [UUID_B, elsewhere],
+ ]);
+ });
+
+ it("keeps markdown images even when the rule would reject their caption", () => {
+ const sequence = collectAttachmentSequence(
+ [{ content: "![报告图表](https://cdn/chart)" }],
+ () => false,
+ );
+ expect(sequence.map((i) => i.key)).toEqual(["https://cdn/chart"]);
+ });
+});
+
describe("indexOfImageKey", () => {
it("finds a key and reports -1 for anything else", () => {
const items = collectImageSequence([
diff --git a/packages/core/attachments/image-sequence.ts b/packages/core/attachments/image-sequence.ts
index 0aa0e57405..0bacb7c2ed 100644
--- a/packages/core/attachments/image-sequence.ts
+++ b/packages/core/attachments/image-sequence.ts
@@ -1,12 +1,11 @@
/**
- * Image sequence — the ordered list of images one surface exposes to the
- * preview viewer's prev / next navigation (MUL-5752).
+ * Attachment sequence — the ordered list of attachments one surface exposes
+ * to the preview viewer's prev / next navigation (MUL-5752, MUL-7642).
*
- * Scope is deliberately narrow: ONLY images. PDFs, video, audio, markdown,
- * HTML and text attachments never enter this sequence — mixing kinds would
- * mean defining per-kind load/keyboard/state semantics for a "next" that can
- * land on a PDF page or a playing video. A non-image attachment simply keeps
- * opening its own single-file preview.
+ * `collectAttachmentSequence` takes the inclusion rule from the caller: web /
+ * desktop page through every previewable kind (images, PDFs, video, Markdown,
+ * HTML, text), so an issue reads as one run of files. `collectImageSequence`
+ * is the images-only rule mobile's lightbox is built on.
*
* The sequence is built from DATA, not from the DOM: both the issue timeline
* and the chat message list are virtualized, so a registry of mounted <img>
@@ -196,18 +195,18 @@ function maskCode(content: string): string {
return lines.join("\n");
}
-interface InlineImageRef {
+interface InlineRef {
index: number;
url: string;
/** Best filename hint available at the reference site. */
filename: string;
/**
- * Whether the reference still has to pass the image test. Markdown `![]()`
+ * `!file[name](url)` card rather than an image reference. Markdown `![]()`
* and `<img>` are images by construction (the renderers pass
- * `forceKind: "image"`); a `!file[name](url)` card only renders as an image
- * when its name/type says so.
+ * `forceKind: "image"`); a card is whatever its name/type says it is, so it
+ * still has to pass the caller's inclusion rule.
*/
- requiresImageCheck: boolean;
+ isFileCard: boolean;
}
// `![alt](url "title")`. The URL char class stops at whitespace and `)` so a
@@ -222,18 +221,18 @@ const HTML_IMAGE_RE =
/<img\b[^>]*?\ssrc\s*=\s*(?:"([^"]*)"|'([^']*)'|([^\s">']+))[^>]*>/gi;
// `!file[name](url)` on its own line — `preprocessFileCards` turns it into a
-// fileCard div, which the renderer hands to <Attachment>; an image filename
-// there renders as an inline image, not a card.
+// fileCard div, which the renderer hands to <Attachment>: an image filename
+// renders as an inline image, anything else as a file card.
const FILE_CARD_LINE_RE = /^[ \t]*!file\[((?:\\.|[^\]\\\n])*)\]\(([^)\s]+)\)[ \t]*$/gm;
function unescapeLabel(label: string): string {
return label.replace(/\\([[\]\\()])/g, "$1");
}
-function extractInlineImageRefs(rawContent: string): InlineImageRef[] {
+function extractInlineRefs(rawContent: string): InlineRef[] {
if (!rawContent) return [];
const content = maskCode(rawContent);
- const refs: InlineImageRef[] = [];
+ const refs: InlineRef[] = [];
for (const m of content.matchAll(MARKDOWN_IMAGE_RE)) {
// Two alternations: `<...>`-wrapped URL (groups 1/2) or bare (groups 3/4).
@@ -244,7 +243,7 @@ function extractInlineImageRefs(rawContent: string): InlineImageRef[] {
index: m.index ?? 0,
url,
filename: unescapeLabel(alt),
- requiresImageCheck: false,
+ isFileCard: false,
});
}
@@ -255,7 +254,7 @@ function extractInlineImageRefs(rawContent: string): InlineImageRef[] {
index: m.index ?? 0,
url,
filename: "",
- requiresImageCheck: false,
+ isFileCard: false,
});
}
@@ -266,7 +265,7 @@ function extractInlineImageRefs(rawContent: string): InlineImageRef[] {
index: m.index ?? 0,
url,
filename: unescapeLabel(m[1] ?? ""),
- requiresImageCheck: true,
+ isFileCard: true,
});
}
@@ -277,12 +276,12 @@ function extractInlineImageRefs(rawContent: string): InlineImageRef[] {
// Sequence
// ---------------------------------------------------------------------------
-/** One image the viewer can page to. */
+/** One attachment the viewer can page to. */
export interface ImageSequenceItem {
/**
- * Identity used to open the sequence at the clicked image. The attachment id
- * when the reference resolves to a record, otherwise the URL as written in
- * the body — matching what the renderer knows at click time.
+ * Identity used to open the sequence at the clicked attachment. The
+ * attachment id when the reference resolves to a record, otherwise the URL
+ * as written in the body — matching what the renderer knows at click time.
*/
key: string;
/** Best-known URL. Callers holding `attachment` should prefer re-resolving. */
@@ -290,24 +289,50 @@ export interface ImageSequenceItem {
filename: string;
/** Present when the reference resolved to a workspace attachment record. */
attachment?: Attachment;
+ /**
+ * The body references this as an image (`![]()` / `<img>`), so it renders
+ * as one whatever `filename` says — for such a reference `filename` is the
+ * markdown caption, which is prose with no extension to read (MUL-7518).
+ */
+ imageByConstruction: boolean;
}
/** One renderable unit: an issue description, a comment, a chat message. */
export interface ImageSequenceBlock {
content?: string | null;
attachments?: ReadonlyArray<Attachment> | null;
+ /**
+ * Whether the surface renders this block's unreferenced attachments as cards
+ * under it. Defaults to true. An issue description renders none, and its
+ * `attachments` is the whole issue's list (comment uploads keep `issue_id`),
+ * so there it only resolves the body's references.
+ */
+ standalone?: boolean;
+}
+
+/** What an inclusion rule gets to decide on. */
+export interface SequenceCandidate {
+ contentType: string;
+ filename: string;
+ /** False for a body reference that did not resolve to an attachment record. */
+ hasRecord: boolean;
}
/**
- * Flatten blocks into the ordered image sequence a viewer walks.
+ * Flatten blocks into the ordered sequence a viewer walks.
+ *
+ * Order is render order: for each block, references inline in the body in
+ * text order, then the standalone attachment cards rendered under it. Repeats
+ * of the same attachment collapse to their first position, so the counter
+ * matches the number of distinct files rather than the number of references.
*
- * Order is render order: for each block, images inline in the body in text
- * order, then the standalone attachment cards rendered under it. Repeats of
- * the same image collapse to their first position, so the counter matches the
- * number of distinct images rather than the number of references.
+ * Image references (`![]()` / `<img>`) are always kept — they render as
+ * images by construction. File cards and standalone attachments are kept
+ * when `include` accepts them.
*/
-export function collectImageSequence(
+export function collectAttachmentSequence(
blocks: ReadonlyArray<ImageSequenceBlock | null | undefined>,
+ include: (candidate: SequenceCandidate) => boolean,
): ImageSequenceItem[] {
const items: ImageSequenceItem[] = [];
const seen = new Set<string>();
@@ -323,13 +348,17 @@ export function collectImageSequence(
const content = block.content ?? "";
const attachments = block.attachments ?? [];
- for (const ref of extractInlineImageRefs(content)) {
+ for (const ref of extractInlineRefs(content)) {
const attachment = matchAttachmentByURL(ref.url, attachments);
- if (ref.requiresImageCheck) {
- const isImage = attachment
- ? isImageAttachment(attachment.content_type, attachment.filename)
- : isImageAttachment("", ref.filename || ref.url);
- if (!isImage) continue;
+ if (
+ ref.isFileCard &&
+ !include({
+ contentType: attachment?.content_type ?? "",
+ filename: attachment?.filename || ref.filename || ref.url,
+ hasRecord: !!attachment,
+ })
+ ) {
+ continue;
}
push({
key: attachment?.id ?? ref.url,
@@ -340,11 +369,19 @@ export function collectImageSequence(
ref.url,
filename: attachment?.filename || ref.filename,
attachment,
+ imageByConstruction: !ref.isFileCard,
});
}
+ if (block.standalone === false) continue;
for (const attachment of selectStandaloneAttachments(content, attachments)) {
- if (!isImageAttachment(attachment.content_type, attachment.filename)) {
+ if (
+ !include({
+ contentType: attachment.content_type,
+ filename: attachment.filename,
+ hasRecord: true,
+ })
+ ) {
continue;
}
push({
@@ -353,6 +390,7 @@ export function collectImageSequence(
attachment.download_url || attachment.markdown_url || attachment.url,
filename: attachment.filename,
attachment,
+ imageByConstruction: false,
});
}
}
@@ -360,6 +398,15 @@ export function collectImageSequence(
return items;
}
+/** The images-only sequence (mobile's lightbox). */
+export function collectImageSequence(
+ blocks: ReadonlyArray<ImageSequenceBlock | null | undefined>,
+): ImageSequenceItem[] {
+ return collectAttachmentSequence(blocks, ({ contentType, filename }) =>
+ isImageAttachment(contentType, filename),
+ );
+}
+
/** Index of `key` in the sequence, or -1 when it is not part of it. */
export function indexOfImageKey(
items: ReadonlyArray<ImageSequenceItem>,
diff --git a/packages/core/attachments/index.ts b/packages/core/attachments/index.ts
index ef2f05ee99..4bfb6600a8 100644
--- a/packages/core/attachments/index.ts
+++ b/packages/core/attachments/index.ts
@@ -1,4 +1,5 @@
export {
+ collectAttachmentSequence,
collectImageSequence,
indexOfImageKey,
isImageAttachment,
@@ -6,4 +7,5 @@ export {
selectStandaloneAttachments,
type ImageSequenceBlock,
type ImageSequenceItem,
+ type SequenceCandidate,
} from "./image-sequence";
diff --git a/packages/views/chat/components/chat-message-list.tsx b/packages/views/chat/components/chat-message-list.tsx
index e8552207c1..292f55c794 100644
--- a/packages/views/chat/components/chat-message-list.tsx
+++ b/packages/views/chat/components/chat-message-list.tsx
@@ -33,8 +33,7 @@ import { RichContent } from "../../rich-content";
import { RichContentScrollRootProvider } from "../../rich-content/scroll-root";
import { copyText } from "@multica/ui/lib/clipboard";
import { AttachmentList } from "../../issues/components/comment-card";
-import { ImageSequenceProvider } from "../../editor";
-import { collectImageSequence } from "@multica/core/attachments/image-sequence";
+import { PreviewSequenceProvider, collectPreviewSequence } from "../../editor";
import type { AgentAvailability } from "@multica/core/agents";
import { resolveFailureReasonKey } from "@multica/core/agents";
import type {
@@ -288,17 +287,17 @@ export function ChatMessageList({
availability,
};
- // Every image in this session, in message order, so opening one lets the
- // reader page through the rest (MUL-5752). Built from the message data, not
- // from what Virtuoso currently has mounted.
+ // Every previewable file in this session, in message order, so opening one
+ // lets the reader page through the rest (MUL-5752). Built from the message
+ // data, not from what Virtuoso currently has mounted.
//
// Persisted messages only: a task transcript's own attachments live behind a
- // separate query and its blocks are collapsed by default, so an image in
- // there keeps its standalone preview instead of entering a sequence the
- // reader can't see the rest of.
- const imageSequence = useMemo(
+ // separate query and its blocks are collapsed by default, so a file in there
+ // keeps its standalone preview instead of entering a sequence the reader
+ // can't see the rest of.
+ const previewSequence = useMemo(
() =>
- collectImageSequence(
+ collectPreviewSequence(
messages.map((message) => ({
content: message.content,
attachments: message.attachments,
@@ -308,7 +307,7 @@ export function ChatMessageList({
);
return (
- <ImageSequenceProvider items={imageSequence}>
+ <PreviewSequenceProvider items={previewSequence}>
<div
ref={setScrollContainerRef}
data-tab-scroll-root
@@ -394,7 +393,7 @@ export function ChatMessageList({
</RichContentScrollRootProvider>
)}
</div>
- </ImageSequenceProvider>
+ </PreviewSequenceProvider>
);
}
diff --git a/packages/views/common/format-bytes.ts b/packages/views/common/format-bytes.ts
new file mode 100644
index 0000000000..46a3b15905
--- /dev/null
+++ b/packages/views/common/format-bytes.ts
@@ -0,0 +1,6 @@
+/** Compact file size for UI metadata: `412 KB`, `3.2 MB`. */
+export function formatBytes(bytes: number): string {
+ if (bytes < 1024) return `${bytes} B`;
+ if (bytes < 1024 * 1024) return `${Math.round(bytes / 1024)} KB`;
+ return `${(bytes / (1024 * 1024)).toFixed(1)} MB`;
+}
diff --git a/packages/views/common/task-transcript/agent-transcript-dialog.tsx b/packages/views/common/task-transcript/agent-transcript-dialog.tsx
index 3beeda987b..6352940cce 100644
--- a/packages/views/common/task-transcript/agent-transcript-dialog.tsx
+++ b/packages/views/common/task-transcript/agent-transcript-dialog.tsx
@@ -101,6 +101,7 @@ import {
formatUsd,
summarizeTaskUsage,
} from "../../runtimes/utils";
+import { formatBytes } from "../format-bytes";
import "../../editor/styles/code.css";
import "./task-transcript.css";
@@ -1843,8 +1844,3 @@ function readPathFromInput(input: Record<string, unknown> | undefined): string |
return typeof path === "string" ? path : undefined;
}
-function formatBytes(bytes: number): string {
- if (bytes < 1024) return `${bytes} B`;
- if (bytes < 1024 * 1024) return `${Math.round(bytes / 1024)} KB`;
- return `${(bytes / (1024 * 1024)).toFixed(1)} MB`;
-}
diff --git a/packages/views/editor/attachment-card.tsx b/packages/views/editor/attachment-card.tsx
index 9349236097..4da1a0acd6 100644
--- a/packages/views/editor/attachment-card.tsx
+++ b/packages/views/editor/attachment-card.tsx
@@ -11,7 +11,7 @@
import { Download, Eye, FileText, Loader2, Trash2 } from "lucide-react";
import { useT } from "../i18n";
-import { getPreviewKind } from "./utils/preview";
+import { canOpenPreview, getPreviewKind } from "./utils/preview";
interface AttachmentCardChromeProps {
filename: string;
@@ -135,15 +135,9 @@ export function AttachmentCard({
onDelete,
}: AttachmentCardProps) {
const kind = filename ? getPreviewKind(contentType, filename) : null;
- // Media kinds (pdf/video/audio) are previewable from a URL alone — the
- // modal renders them as <video>/<audio>/<iframe src=url>. Text kinds
- // (markdown/html/text) need the ID-keyed `/api/attachments/{id}/content`
- // proxy, so they only preview when we have an attachmentId — otherwise
+ // Without an attachmentId only the URL-renderable kinds open — otherwise
// the Eye button would call tryOpen, get rejected, and do nothing.
- const isUrlPreviewableKind =
- kind === "pdf" || kind === "video" || kind === "audio";
- const canPreview =
- !!href && kind !== null && (!!attachmentId || isUrlPreviewableKind);
+ const canPreview = !!href && canOpenPreview(kind, !!attachmentId);
return (
<div className="my-1">
diff --git a/packages/views/editor/attachment-preview-modal.test.tsx b/packages/views/editor/attachment-preview-modal.test.tsx
index 6fe14fef73..788b63dbb7 100644
--- a/packages/views/editor/attachment-preview-modal.test.tsx
+++ b/packages/views/editor/attachment-preview-modal.test.tsx
@@ -16,6 +16,7 @@ vi.mock("../platform", () => ({
// declarations.
const {
getAttachmentTextContentMock,
+ getAttachmentMock,
downloadMock,
getBaseUrlMock,
FakePreviewTooLargeError,
@@ -35,6 +36,9 @@ const {
}
return {
getAttachmentTextContentMock: vi.fn(),
+ // Re-sign metadata. Rejects by default: a deployment with nothing to
+ // upgrade to, so the picked URL stands.
+ getAttachmentMock: vi.fn((): Promise<Attachment> => Promise.reject(new Error("no re-sign"))),
downloadMock: vi.fn(),
// Default to the web shape (empty base, same-origin). Tests covering
// the desktop-renderer / standalone-shell case override per-test.
@@ -47,6 +51,7 @@ const {
vi.mock("@multica/core/api", () => ({
api: {
getAttachmentTextContent: getAttachmentTextContentMock,
+ getAttachment: getAttachmentMock,
getBaseUrl: getBaseUrlMock,
},
PreviewTooLargeError: FakePreviewTooLargeError,
@@ -319,7 +324,7 @@ describe("AttachmentPreviewModal — server-relative download_url resolution (MU
// is loaded from `app://` / file: / dev-server origin and needs the
// absolute URL — otherwise `<img src>`, `<iframe src>`, `<video src>`
// hit the shell origin and fail.
- it("prefixes the configured API base for image previews when download_url is server-relative", () => {
+ it("prefixes the configured API base for image previews when download_url is server-relative", async () => {
getBaseUrlMock.mockReturnValue("https://api.example.test");
const att = makeAttachment({
filename: "shot.png",
@@ -333,10 +338,55 @@ describe("AttachmentPreviewModal — server-relative download_url resolution (MU
onClose={() => {}}
/>,
);
- const img = document.querySelector("img");
- expect(img?.getAttribute("src")).toBe(
- "https://api.example.test/api/attachments/att-1/download",
+ // The auth-gated endpoint is only handed to <img> once the re-sign has
+ // settled (here: nothing better on offer).
+ await waitFor(() => {
+ expect(document.querySelector("img")?.getAttribute("src")).toBe(
+ "https://api.example.test/api/attachments/att-1/download",
+ );
+ });
+ });
+
+ // A client that cannot load the auth-gated endpoint natively (desktop,
+ // split-origin web) would fail on it, and a sequence reads that failure as
+ // a broken image and skips it. Nothing reaches <img> until the upgrade lands.
+ it("waits for the re-sign before loading an auth-gated image", async () => {
+ getBaseUrlMock.mockReturnValue("https://api.example.test");
+ let resolveMeta: (value: Attachment) => void = () => {};
+ getAttachmentMock.mockImplementationOnce(
+ () => new Promise<Attachment>((resolve) => { resolveMeta = resolve; }),
+ );
+ const onImageError = vi.fn();
+ // A real id: only the stable `/api/attachments/<uuid>/download` shape is
+ // recognised as the auth-gated endpoint.
+ const id = "11111111-1111-4111-8111-111111111111";
+ const att = makeAttachment({
+ id,
+ filename: "shot.png",
+ content_type: "image/png",
+ download_url: `/api/attachments/${id}/download`,
+ });
+ render(
+ <AttachmentPreviewModal
+ source={{ kind: "full", attachment: att }}
+ open
+ onClose={() => {}}
+ onImageError={onImageError}
+ />,
);
+
+ expect(screen.getByRole("dialog").querySelector("img")).toBeNull();
+ expect(screen.getByText("Loading preview…")).toBeInTheDocument();
+
+ await act(async () => {
+ resolveMeta({ ...att, download_url: "https://cdn.example.test/att-1.png?Signature=fresh" });
+ });
+ await waitFor(() => {
+ expect(screen.getByRole("dialog").querySelector("img")?.getAttribute("src")).toBe(
+ "https://cdn.example.test/att-1.png?Signature=fresh",
+ );
+ });
+ expect(onImageError).not.toHaveBeenCalled();
});
it("prefixes the configured API base for PDF previews when download_url is server-relative", () => {
@@ -470,6 +520,34 @@ describe("AttachmentPreviewModal — controls", () => {
expect(downloadMock).toHaveBeenCalledWith("att-1");
});
+ it("describes the file by type and size instead of its MIME type", () => {
+ const att = makeAttachment({
+ filename: "manual.pdf",
+ content_type: "application/pdf",
+ size_bytes: 2 * 1024 * 1024,
+ });
+ render(<AttachmentPreviewModal source={{ kind: "full", attachment: att }} open onClose={() => {}} />);
+ expect(screen.getByText("PDF · 2.0 MB")).toBeInTheDocument();
+ expect(screen.queryByText("application/pdf")).toBeNull();
+ });
+
+ it("hides the desktop window buttons while open and restores them on close", async () => {
+ const setImmersiveMode = vi.fn();
+ (window as unknown as { desktopAPI?: unknown }).desktopAPI = { setImmersiveMode };
+ try {
+ const att = makeAttachment({ filename: "manual.pdf", content_type: "application/pdf" });
+ render(<ClosablePreview attachment={att} />);
+ expect(setImmersiveMode).toHaveBeenLastCalledWith(true);
+
+ fireEvent.click(screen.getByTitle("Close"));
+ await waitFor(() => {
+ expect(setImmersiveMode).toHaveBeenLastCalledWith(false);
+ });
+ } finally {
+ delete (window as unknown as { desktopAPI?: unknown }).desktopAPI;
+ }
+ });
+
it("clicking the backdrop closes the modal", () => {
const onClose = vi.fn();
const att = makeAttachment({ filename: "manual.pdf", content_type: "application/pdf" });
@@ -932,6 +1010,18 @@ describe("AttachmentPreviewModal — image zoom", () => {
expect(currentScale()).toBeCloseTo(0.5 * 1.2, 5);
});
+ // The focus placed on open is for the keyboard controls; drawn as a ring it
+ // framed the whole full-window stage. It stays marked (CSS drops the ring)
+ // until focus leaves, so a reader tabbing back in still sees one.
+ it("keeps the focus ring off for the focus it places itself", () => {
+ stubNaturalSize({ width: 1600, height: 800 });
+ renderImagePreview();
+
+ expect(zoomCanvas()).toHaveAttribute("data-autofocused");
+ fireEvent.blur(zoomCanvas());
+ expect(zoomCanvas()).not.toHaveAttribute("data-autofocused");
+ });
+
it("re-fits on reopen instead of restoring the previous zoom", async () => {
stubNaturalSize({ width: 1600, height: 800 });
const att = imageAttachment();
diff --git a/packages/views/editor/attachment-preview-modal.tsx b/packages/views/editor/attachment-preview-modal.tsx
index 5ea4bcd8a3..21fee817ab 100644
--- a/packages/views/editor/attachment-preview-modal.tsx
+++ b/packages/views/editor/attachment-preview-modal.tsx
@@ -1,14 +1,21 @@
"use client";
/**
- * AttachmentPreviewModal — full-screen inline preview for an attachment.
+ * AttachmentPreviewModal — full-window viewer for an attachment.
*
- * Single modal for every previewable kind. Handles 7 PreviewKinds:
+ * The file gets the whole window (MUL-7642): no card, no max width. A fixed
+ * near-black stage sits behind the content whatever the theme — a photo, a
+ * PDF page and a white HTML document all read against it — and the chrome
+ * over it (top bar, prev / next, messages on the stage) wears the dark token
+ * set via a `dark` class on each chrome element. Documents that are read
+ * rather than looked at (Markdown, text) render on a centered sheet that
+ * keeps the app's own theme.
+ *
+ * Single viewer for every previewable kind. Handles 7 PreviewKinds:
*
* - image : <img> on the shared ZoomCanvas — fit on open, then wheel /
* drag / pinch / double-click / keyboard zoom, same controls as
- * the Mermaid viewer. Replaces the previous standalone
- * ImageLightbox.
+ * the Mermaid viewer.
* - pdf : <iframe src={download_url}> — relies on Chromium's PDFium
* plugin. On desktop, requires webPreferences.plugins=true
* (see apps/desktop/src/main/index.ts).
@@ -38,6 +45,7 @@ import {
useMemo,
useRef,
useState,
+ type CSSProperties,
type ReactNode,
} from "react";
import { createPortal } from "react-dom";
@@ -51,9 +59,15 @@ import {
ChevronRight,
Download,
ExternalLink,
+ File,
+ FileAudio,
+ FileCode,
FileText,
+ FileVideo,
+ ImageIcon,
Loader2,
X,
+ type LucideIcon,
} from "lucide-react";
import type { Attachment } from "@multica/core/types";
import { paths, useWorkspaceSlug } from "@multica/core/paths";
@@ -66,15 +80,19 @@ import {
import { useT } from "../i18n";
import { useNavigation } from "../navigation";
import { openExternal } from "../platform";
+import { useImmersiveMode } from "../platform/use-immersive-mode";
import { ReadonlyContent } from "./readonly-content";
import {
+ canOpenPreview,
extensionToLanguage,
+ fileTypeLabel,
getPreviewKind,
type PreviewKind,
} from "./utils/preview";
+import { formatBytes } from "../common/format-bytes";
import { useDownloadAttachment } from "./use-download-attachment";
import { useAttachmentHtmlText } from "./hooks/use-attachment-html-text";
-import { useResignedInlineMediaURL } from "./hooks/use-inline-media-url";
+import { useResignedInlineMedia } from "./hooks/use-inline-media-url";
import { useZoomCanvas, type ZoomCanvasApi } from "./hooks/use-zoom-canvas";
import { ZoomCanvas, ZoomControls } from "./zoom-canvas";
import type { Size } from "./utils/zoom-transform";
@@ -114,10 +132,6 @@ export type PreviewSource =
forceKind?: PreviewKind;
};
-// 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>(["image", "pdf", "video", "audio"]);
-
// Normalized view used everywhere downstream of `useAttachmentPreview`.
// `attachmentId === null` signals URL-only mode (download falls back to
// `openExternal`, text rendering branches are unreachable by the gate).
@@ -126,6 +140,8 @@ interface PreviewState {
contentType: string;
mediaUrl: string;
attachmentId: string | null;
+ /** 0 when unknown (URL-only source). */
+ sizeBytes: number;
/**
* The kind every consumer dispatches on — resolved once, here, so the
* tryOpen gate and the rendered panel can never disagree about what the
@@ -156,6 +172,7 @@ function normalize(source: PreviewSource): PreviewState {
contentType: source.attachment.content_type,
mediaUrl: resolvePreviewMediaUrl(source.attachment),
attachmentId: source.attachment.id,
+ sizeBytes: source.attachment.size_bytes,
kind: getPreviewKind(
source.attachment.content_type,
source.attachment.filename,
@@ -167,6 +184,7 @@ function normalize(source: PreviewSource): PreviewState {
contentType: "",
mediaUrl: resolvePublicFileUrl(source.url) ?? source.url,
attachmentId: null,
+ sizeBytes: 0,
kind: source.forceKind ?? getPreviewKind("", source.filename),
};
}
@@ -237,9 +255,8 @@ export function useAttachmentPreview(): AttachmentPreviewHandle {
}, []);
const tryOpen = useCallback((source: PreviewSource) => {
const { kind } = normalize(source);
- if (!kind) return false;
// URL-only sources cannot drive text kinds — the /content proxy is ID-keyed.
- if (source.kind === "url" && !URL_ONLY_KINDS.has(kind)) return false;
+ if (!canOpenPreview(kind, source.kind === "full")) return false;
setCurrent(source);
setPreviewOpen(true);
return true;
@@ -270,6 +287,11 @@ export function useAttachmentPreview(): AttachmentPreviewHandle {
// panel) the moment navigation happens blanks the canvas for the full
// network+decode gap; decode-then-swap is the standard lightbox fix.
//
+// Only a URL that actually decoded as an image is ever held. The panel is
+// reused across kinds, so arriving at an image from a PDF or a document has no
+// previous frame: the image shows as itself and loads in place — handing the
+// PDF's URL to <img> would fail and be blamed on the image being opened.
+//
// On load failure the hook reports the error and keeps the last good frame —
// when the whole remaining sequence is broken the reader stays on the last
// image that worked (with the "unavailable" toast) instead of a broken glyph.
@@ -281,16 +303,18 @@ function useSettledImageURL(
enabled: boolean,
onLoadError?: () => void,
): string {
- const [settled, setSettled] = useState(targetUrl);
+ const [settled, setSettled] = useState<string | null>(null);
const onErrorRef = useRef(onLoadError);
onErrorRef.current = onLoadError;
useEffect(() => {
- if (!enabled) return;
- if (!targetUrl) {
- setSettled(targetUrl);
+ if (!enabled) {
+ setSettled(null);
return;
}
+ // Nothing loadable yet (the URL is still being re-signed): keep holding
+ // whatever frame is up.
+ if (!targetUrl) return;
let cancelled = false;
const probe = new window.Image();
if (typeof probe.decode !== "function") {
@@ -312,7 +336,7 @@ function useSettledImageURL(
};
}, [targetUrl, enabled]);
- return enabled ? settled : targetUrl;
+ return enabled && settled !== null ? settled : targetUrl;
}
// Warms the browser cache for a sequence neighbour so paging to it swaps
@@ -320,25 +344,41 @@ function useSettledImageURL(
// then fetches the bytes through a detached <img>. Renders nothing.
export function PreviewImagePrefetch({ source }: { source: PreviewSource }) {
const state = normalize(source);
- const url = useResignedInlineMediaURL(
+ const { url, pending } = useResignedInlineMedia(
state.attachmentId ?? undefined,
state.mediaUrl,
true,
);
useEffect(() => {
- if (!url) return;
+ if (!url || pending) return;
const probe = new window.Image();
probe.src = url;
- }, [url]);
+ }, [url, pending]);
return null;
}
// ---------------------------------------------------------------------------
-// Modal — frame + dispatch
+// Viewer — frame + dispatch
// ---------------------------------------------------------------------------
+// Desktop window chrome. The viewer covers the whole window, including the
+// top bar's drag region, so it declares its own: the viewer is `no-drag`
+// (a drag region underneath would otherwise swallow clicks on its controls),
+// its top bar drags the window, and the controls in that bar opt back out.
+// Chromium-only CSS; browsers ignore it.
+const NO_DRAG = { WebkitAppRegion: "no-drag" } as CSSProperties;
+const DRAG = { WebkitAppRegion: "drag" } as CSSProperties;
+
+// A focused player or field owns its arrow keys (seek, caret) — the sequence
+// only takes them when nothing else would.
+function ownsArrowKeys(target: EventTarget | null): boolean {
+ if (!(target instanceof HTMLElement)) return false;
+ if (target.isContentEditable) return true;
+ return target.closest("input, textarea, select, video, audio") !== null;
+}
+
export function AttachmentPreviewModal({
source,
open,
@@ -358,6 +398,11 @@ export function AttachmentPreviewModal({
const onPrev = sequence?.onPrev;
const onNext = sequence?.onNext;
+ // macOS desktop: hide the traffic lights while the viewer is up — its top
+ // bar starts at the window's top-left corner, where they would sit on the
+ // file name. No-op on web and other platforms.
+ useImmersiveMode(open);
+
useEffect(() => {
if (!open) return;
const handler = (e: KeyboardEvent) => {
@@ -370,6 +415,7 @@ export function AttachmentPreviewModal({
// `horizontalArrowPan` below), so exactly one of the two responds.
// Modified presses stay with the browser / OS.
if (e.metaKey || e.ctrlKey || e.altKey || e.shiftKey) return;
+ if (ownsArrowKeys(e.target)) return;
if (e.key === "ArrowLeft" && onPrev) {
e.preventDefault();
onPrev();
@@ -421,7 +467,9 @@ export function AttachmentPreviewModal({
<AnimatePresence onExitComplete={onExitComplete}>
{open && (
<motion.div
- className="fixed inset-0 z-50 flex items-center justify-center bg-black/80 p-4"
+ // Blurred as well as dimmed: at any opacity that still reads as a
+ // backdrop, the page's text shows through behind the top bar.
+ className="fixed inset-0 z-50 flex flex-col bg-black/95 backdrop-blur-xl"
// Only a click that lands on the backdrop itself closes. A pan that
// starts on the zoom canvas and releases out here retargets its
// click through pointer capture, but this makes the intent explicit
@@ -432,6 +480,7 @@ export function AttachmentPreviewModal({
role="dialog"
aria-modal="true"
aria-label={state.filename}
+ style={NO_DRAG}
initial={{ opacity: 0 }}
animate={{
opacity: 1,
@@ -448,56 +497,28 @@ export function AttachmentPreviewModal({
},
}}
>
- {/* Larger than the create-issue dialog (max-w-4xl, manualDialogContentClass)
- because PDF / video previews want more room. Capped to viewport
- minus the surrounding p-4 (1rem each side) so it never overflows
- the screen on small displays / split panes. */}
- <motion.div
- className="flex h-[min(90vh,calc(100vh-2rem))] w-full max-w-6xl flex-col overflow-hidden rounded-lg bg-background shadow-xl"
- onClick={(e) => e.stopPropagation()}
- initial={{
- opacity: 0,
- transform: shouldReduceMotion ? "scale(1)" : "scale(0.95)",
- }}
- animate={{
- opacity: 1,
- transform: "scale(1)",
- transition: {
- duration: UI_MOTION_DURATION.standard,
- ease: UI_EASE_OUT,
- },
- }}
- exit={{
- opacity: 0,
- transform: shouldReduceMotion ? "scale(1)" : "scale(0.95)",
- transition: {
- duration: UI_MOTION_DURATION.fast,
- ease: UI_EASE_OUT,
- },
- }}
- >
- {/* Below the `open &&` gate on purpose: the panel's zoom state is
- destroyed on close, so every open re-fits instead of restoring
- a stale zoom from the last time this image was viewed.
-
- Deliberately NOT keyed on the file: remounting the panel on
- sequence navigation blanks the canvas for the whole
- network+decode gap. The panel persists and swaps the image
- only once the next one has decoded (`useSettledImageURL`).
- Zoom still resets per image — `natural` passes through null on
- every swap, so the canvas re-fits even across a run of
- same-resolution screenshots. */}
- <PreviewPanel
- kind={kind}
- source={source}
- state={state}
- onClose={onClose}
- onDownload={handleDownload}
- onOpenInNewTab={canOpenInNewTab ? handleOpenInNewTab : undefined}
- sequence={sequence}
- onImageError={onImageError}
- />
- </motion.div>
+ {/* Below the `open &&` gate on purpose: the panel's zoom state is
+ destroyed on close, so every open re-fits instead of restoring
+ a stale zoom from the last time this image was viewed.
+
+ Deliberately NOT keyed on the file: remounting the panel on
+ sequence navigation blanks the canvas for the whole
+ network+decode gap. The panel persists and swaps the image
+ only once the next one has decoded (`useSettledImageURL`).
+ Zoom still resets per image — `natural` passes through null on
+ every swap, so the canvas re-fits even across a run of
+ same-resolution screenshots. */}
+ <PreviewPanel
+ kind={kind}
+ source={source}
+ state={state}
+ onClose={onClose}
+ onDownload={handleDownload}
+ onOpenInNewTab={canOpenInNewTab ? handleOpenInNewTab : undefined}
+ sequence={sequence}
+ onImageError={onImageError}
+ reduceMotion={shouldReduceMotion}
+ />
</motion.div>
)}
</AnimatePresence>,
@@ -506,12 +527,22 @@ export function AttachmentPreviewModal({
}
// ---------------------------------------------------------------------------
-// Panel — header + content area
+// Panel — top bar + stage
// ---------------------------------------------------------------------------
-// Header chrome and the content area live together because the image kind's
-// zoom controls sit in the header while the canvas they drive is the body:
-// one owner for that shared state, mounted and destroyed with the open modal.
+const KIND_ICONS: Record<PreviewKind, LucideIcon> = {
+ image: ImageIcon,
+ pdf: FileText,
+ video: FileVideo,
+ audio: FileAudio,
+ markdown: FileText,
+ html: FileCode,
+ text: FileCode,
+};
+
+// Top bar and stage live together because the image kind's zoom controls sit
+// in the bar while the canvas they drive is on the stage: one owner for that
+// shared state, mounted and destroyed with the open viewer.
function PreviewPanel({
kind,
source,
@@ -521,6 +552,7 @@ function PreviewPanel({
onOpenInNewTab,
sequence,
onImageError,
+ reduceMotion,
}: {
kind: PreviewKind | null;
source: PreviewSource;
@@ -530,22 +562,33 @@ function PreviewPanel({
onOpenInNewTab?: () => void;
sequence?: PreviewSequence;
onImageError?: () => void;
+ reduceMotion: boolean;
}) {
const { t } = useT("editor");
// Gallery navigation hands this panel an attachment the reader never
// clicked, so — unlike the click-through path, where <Attachment> had
- // already upgraded the URL — the modal has to run the re-sign itself. A
+ // already upgraded the URL — the viewer has to run the re-sign itself. A
// no-op for URLs that are already loadable (signed CDN, public storage).
- const targetUrl = useResignedInlineMediaURL(
+ const resigned = useResignedInlineMedia(
state.attachmentId ?? undefined,
state.mediaUrl,
kind === "image",
);
+ // Until that upgrade lands the picked URL may be one this client cannot
+ // load natively (desktop, split-origin web); handed to <img> it would fail
+ // and, in a sequence, read as a broken image to skip. Hold the previous
+ // frame — or show loading — instead.
+ const targetUrl = resigned.pending ? "" : resigned.url;
// The previous image stays on the canvas until this one has decoded — the
// swap itself is what used to flash. Also absorbs the re-sign URL upgrade
// (raw -> signed) without a second visible load.
const mediaUrl = useSettledImageURL(targetUrl, kind === "image", onImageError);
+ // A load error from the <img> belongs to the file being opened only when
+ // that is what it shows — a frame held from the previous image never
+ // reports against the next one.
+ const imageLoadError =
+ mediaUrl !== "" && mediaUrl === targetUrl ? onImageError : undefined;
// Natural size is carried with the URL it was measured from, so a panel
// reused for a different attachment can never fit the new image against the
@@ -576,48 +619,57 @@ function PreviewPanel({
[],
);
+ // What the reader wants to know about the file at a glance — type, pixel
+ // size, weight. Not the MIME type: `image/png` says nothing `PNG` doesn't.
+ const meta = [
+ fileTypeLabel(state.filename),
+ natural ? `${natural.width} × ${natural.height}` : "",
+ state.sizeBytes > 0 ? formatBytes(state.sizeBytes) : "",
+ ].filter(Boolean);
+ const KindIcon = kind ? KIND_ICONS[kind] : File;
+
+ // The stage's own padding — the gutters around the content — counts as
+ // backdrop: clicking there closes, clicking the content never does.
+ const closeOnBackdrop = (e: React.MouseEvent) => {
+ if (e.target === e.currentTarget) onClose();
+ };
+
return (
<>
- <div className="flex items-center gap-2 border-b border-border bg-muted/30 px-4 py-2">
- <FileText className="size-4 shrink-0 text-muted-foreground" />
- {/* Baseline group: filename (text-body) and type (text-caption) are
- different type sizes on one line — the row's items-center would
- center their unequal line boxes and visibly offset the smaller
- text. Mixed-size text aligns by baseline. */}
- <div className="flex min-w-0 items-baseline gap-2">
- <p className="truncate text-body font-medium">{state.filename}</p>
- <span className="shrink-0 text-caption text-muted-foreground">
- {state.contentType || "—"}
+ {/* Three columns so the counter stays centered on the window while a
+ long filename truncates before reaching it. */}
+ <header
+ className="dark grid h-14 shrink-0 grid-cols-[minmax(0,1fr)_auto_minmax(0,1fr)] items-center gap-4 pl-3 pr-2 text-foreground"
+ style={DRAG}
+ >
+ <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">
+ <KindIcon className="size-4" />
</span>
+ <div className="min-w-0">
+ <p className="truncate text-body font-medium">{state.filename}</p>
+ {meta.length > 0 && (
+ <p className="truncate text-caption text-muted-foreground tabular-nums">
+ {meta.join(" · ")}
+ </p>
+ )}
+ </div>
</div>
- <div className="ml-auto flex items-center gap-1">
- {/* Navigation leads the action cluster, arrows off the image
- (they covered exactly the content being looked at) and the
- counter between the arrows it describes. min-w keeps the
- arrows from shifting as digit counts change. */}
- {sequence && (
- <div className="mr-1 flex shrink-0 items-center gap-0.5">
- <SequenceButton
- side="prev"
- label={t(($) => $.image.previous)}
- onClick={sequence.onPrev}
- />
- <span
- className="min-w-10 select-none text-center text-caption tabular-nums text-muted-foreground"
- aria-live="polite"
- >
- {t(($) => $.image.sequence_position, {
- index: sequence.index + 1,
- total: sequence.total,
- })}
- </span>
- <SequenceButton
- side="next"
- label={t(($) => $.image.next)}
- onClick={sequence.onNext}
- />
- </div>
- )}
+ <span
+ className="select-none text-label tabular-nums text-muted-foreground"
+ aria-live="polite"
+ >
+ {sequence
+ ? t(($) => $.attachment.sequence_position, {
+ index: sequence.index + 1,
+ total: sequence.total,
+ })
+ : null}
+ </span>
+ <div
+ className="flex items-center justify-self-end gap-0.5"
+ style={NO_DRAG}
+ >
{/* Standalone preview keeps the original gate — no controls until
the image is measured, and none at all for content that has no
intrinsic size to drive. In a sequence they stay mounted
@@ -625,51 +677,45 @@ function PreviewPanel({
null on every swap, and controls that vanish and reappear shift
the buttons to their right on every navigation. */}
{kind === "image" && (natural || sequence) && (
- <ZoomControls canvas={canvas} disabled={!natural} />
+ <>
+ <ZoomControls canvas={canvas} disabled={!natural} />
+ <ChromeDivider />
+ </>
)}
{onOpenInNewTab && (
- <button
- type="button"
- className="rounded-md p-1.5 text-muted-foreground transition-colors hover:bg-secondary hover:text-foreground"
- title={t(($) => $.attachment.open_in_new_tab)}
- aria-label={t(($) => $.attachment.open_in_new_tab)}
+ <ChromeButton
+ label={t(($) => $.attachment.open_in_new_tab)}
onClick={onOpenInNewTab}
>
<ExternalLink className="size-4" />
- </button>
+ </ChromeButton>
)}
- <button
- type="button"
- className="rounded-md p-1.5 text-muted-foreground transition-colors hover:bg-secondary hover:text-foreground"
- title={t(($) => $.image.download)}
- aria-label={t(($) => $.image.download)}
- onClick={onDownload}
- >
+ <ChromeButton label={t(($) => $.image.download)} onClick={onDownload}>
<Download className="size-4" />
- </button>
- <button
- type="button"
- className="rounded-md p-1.5 text-muted-foreground transition-colors hover:bg-secondary hover:text-foreground"
- title={t(($) => $.attachment.close)}
- aria-label={t(($) => $.attachment.close)}
- onClick={onClose}
- >
+ </ChromeButton>
+ <ChromeDivider />
+ <ChromeButton label={t(($) => $.attachment.close)} onClick={onClose}>
<X className="size-4" />
- </button>
+ </ChromeButton>
</div>
- </div>
- {/* Image gets a flex column: the canvas sizes itself with `flex: 1 1
- auto` and its content is absolutely positioned, so in a plain block
- parent it would collapse to zero height and show nothing. It also
- clips and handles its own wheel events — letting this wrapper scroll
- too would fight the pan. Every other kind keeps the block scroller;
- making them flex items would let tall text previews shrink to fit
- instead of scrolling. */}
- <div
+ </header>
+ {/* The stage. In a sequence its sides are 64px gutters holding the
+ prev / next buttons, so a fitted image or a page never runs under
+ them. */}
+ <motion.div
className={cn(
- "relative min-h-0 flex-1 bg-background",
- kind === "image" ? "flex flex-col overflow-hidden" : "overflow-auto",
+ "relative min-h-0 flex-1",
+ sequence ? "px-16" : "px-4",
)}
+ onClick={closeOnBackdrop}
+ initial={{ transform: reduceMotion ? "scale(1)" : "scale(0.97)" }}
+ animate={{
+ transform: "scale(1)",
+ transition: {
+ duration: UI_MOTION_DURATION.standard,
+ ease: UI_EASE_OUT,
+ },
+ }}
>
{kind === "image" ? (
<ImagePreview
@@ -678,7 +724,7 @@ function PreviewPanel({
canvas={canvas}
natural={natural}
onNaturalSize={handleNaturalSize}
- onError={onImageError}
+ onError={imageLoadError}
/>
) : (
<PreviewContent
@@ -686,23 +732,65 @@ function PreviewPanel({
source={source}
state={state}
onDownload={onDownload}
+ onBackdropClick={closeOnBackdrop}
/>
)}
- </div>
+ {sequence && (
+ <>
+ <SequenceButton
+ side="prev"
+ label={t(($) => $.attachment.previous)}
+ onClick={sequence.onPrev}
+ />
+ <SequenceButton
+ side="next"
+ label={t(($) => $.attachment.next)}
+ onClick={sequence.onNext}
+ />
+ </>
+ )}
+ </motion.div>
</>
);
}
// ---------------------------------------------------------------------------
-// Sequence controls
+// Chrome controls
// ---------------------------------------------------------------------------
-// Header chevrons in the same idiom as the download/close buttons. `onClick`
-// undefined means "boundary reached": the button stays mounted but disabled,
-// so the reader can see they are at one end instead of the control vanishing
-// and shifting the counter into its place. `enabled:hover` so the disabled
-// state gets no hover feedback (and no pointer-events-none — a disabled
-// control should still catch the cursor and read as "nothing here").
+// 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({
+ label,
+ onClick,
+ children,
+}: {
+ label: string;
+ onClick: () => void;
+ children: ReactNode;
+}) {
+ return (
+ <button
+ type="button"
+ className="flex size-8 items-center justify-center rounded-md text-muted-foreground transition-colors hover:bg-secondary hover:text-foreground"
+ title={label}
+ aria-label={label}
+ onClick={onClick}
+ >
+ {children}
+ </button>
+ );
+}
+
+function ChromeDivider() {
+ return <span className="mx-1.5 h-4 w-px bg-input" aria-hidden />;
+}
+
+// Prev / next in the stage gutters, vertically centered — next to the
+// content, never on it. `onClick` undefined means "boundary reached": the
+// button stays mounted but disabled, so the reader can see they are at one
+// end instead of the control vanishing. `enabled:hover` so the disabled state
+// gets no hover feedback.
function SequenceButton({
side,
label,
@@ -716,13 +804,16 @@ function SequenceButton({
return (
<button
type="button"
- className="rounded-md p-1.5 text-muted-foreground transition-colors enabled:hover:bg-secondary enabled:hover:text-foreground disabled:opacity-30"
+ className={cn(
+ "dark absolute top-1/2 flex size-10 -translate-y-1/2 items-center justify-center rounded-full bg-secondary/80 text-foreground transition-colors enabled:hover:bg-secondary disabled:opacity-30",
+ side === "prev" ? "left-3" : "right-3",
+ )}
title={label}
aria-label={label}
disabled={!onClick}
onClick={onClick}
>
- <Icon className="size-4" />
+ <Icon className="size-5" />
</button>
);
}
@@ -764,32 +855,46 @@ function ImagePreview({
[onNaturalSize, url],
);
+ if (!url) {
+ return (
+ <div className="dark flex h-full items-center justify-center gap-2 text-body text-muted-foreground">
+ <Loader2 className="size-4 animate-spin" />
+ {t(($) => $.attachment.preview_loading)}
+ </div>
+ );
+ }
+
+ // A flex column: the canvas sizes itself with `flex: 1 1 auto` and its
+ // content is absolutely positioned, so in a plain block parent it would
+ // collapse to zero height and show nothing. It clips and handles its own
+ // wheel events.
return (
- <ZoomCanvas
- canvas={canvas}
- content={natural}
- label={t(($) => $.image.canvas_label)}
- className="bg-black/40"
- autoFocus
- >
- <img
- // A cached image is already `complete` before React attaches onLoad,
- // so that event never fires — measure from the ref as well.
- ref={readNaturalSize}
- onLoad={(e) => readNaturalSize(e.currentTarget)}
- onError={onError}
- src={url}
- alt={state.filename}
- className={cn(
- "select-none",
- natural
- ? "block size-full"
- : "max-h-full max-w-full rounded-lg object-contain",
- )}
- // Native image dragging would hijack the pan gesture.
- draggable={false}
- />
- </ZoomCanvas>
+ <div className="flex h-full flex-col py-4">
+ <ZoomCanvas
+ canvas={canvas}
+ content={natural}
+ label={t(($) => $.image.canvas_label)}
+ autoFocus
+ >
+ <img
+ // A cached image is already `complete` before React attaches onLoad,
+ // so that event never fires — measure from the ref as well.
+ ref={readNaturalSize}
+ onLoad={(e) => readNaturalSize(e.currentTarget)}
+ onError={onError}
+ src={url}
+ alt={state.filename}
+ className={cn(
+ "select-none",
+ natural
+ ? "block size-full"
+ : "max-h-full max-w-full rounded-lg object-contain",
+ )}
+ // Native image dragging would hijack the pan gesture.
+ draggable={false}
+ />
+ </ZoomCanvas>
+ </div>
);
}
@@ -797,20 +902,26 @@ function ImagePreview({
// Dispatch
// ---------------------------------------------------------------------------
-// Dispatch on PreviewKind. New cases go here; remember that the modal frame
-// (header, close, Download CTA, ESC handling) is shared — sub-renderers only
-// own the content area. `image` is handled by PreviewPanel itself because its
+// Dispatch on PreviewKind. New cases go here; remember that the viewer frame
+// (top bar, close, Download CTA, ESC handling) is shared — sub-renderers only
+// own the stage. `image` is handled by PreviewPanel itself because its
// toolbar and canvas share zoom state.
+//
+// Layout per kind: pages (PDF, HTML) fill the stage; video letterboxes on it;
+// Markdown and text scroll on a centered sheet in the app's own theme; anything
+// else that sits directly on the stage wears `dark`.
function PreviewContent({
kind,
source,
state,
onDownload,
+ onBackdropClick,
}: {
kind: Exclude<PreviewKind, "image"> | null;
source: PreviewSource;
state: PreviewState;
onDownload: () => void;
+ onBackdropClick: (e: React.MouseEvent) => void;
}) {
const { t } = useT("editor");
@@ -843,15 +954,17 @@ function PreviewContent({
switch (kind) {
case "pdf":
return (
- <iframe
- src={state.mediaUrl}
- className="h-full w-full bg-background"
- title={state.filename}
- />
+ <div className="h-full pb-4">
+ <iframe
+ src={state.mediaUrl}
+ className="h-full w-full rounded-lg bg-background"
+ title={state.filename}
+ />
+ </div>
);
case "video":
return (
- <div className="flex h-full w-full items-center justify-center bg-black">
+ <div className="flex h-full w-full items-center justify-center pb-4">
<video
src={state.mediaUrl}
controls
@@ -861,7 +974,7 @@ function PreviewContent({
);
case "audio":
return (
- <div className="flex h-full w-full items-center justify-center p-8">
+ <div className="dark flex h-full w-full items-center justify-center p-8">
<audio src={state.mediaUrl} controls className="w-full max-w-xl" />
</div>
);
@@ -871,11 +984,13 @@ function PreviewContent({
attachmentId={state.attachmentId!}
onDownload={onDownload}
render={(text) => (
- <ReadonlyContent
- content={text}
- className="px-6 py-4"
- attachments={source.kind === "full" ? [source.attachment] : []}
- />
+ <DocumentSheet width="prose" onBackdropClick={onBackdropClick}>
+ <ReadonlyContent
+ content={text}
+ className="px-10 py-8"
+ attachments={source.kind === "full" ? [source.attachment] : []}
+ />
+ </DocumentSheet>
)}
/>
);
@@ -885,12 +1000,14 @@ function PreviewContent({
attachmentId={state.attachmentId!}
onDownload={onDownload}
render={(text) => (
- <HtmlPreviewBody
- source={{ kind: "inline", html: text }}
- title={state.filename}
- className="h-full w-full"
- iframeClassName="rounded-none border-0"
- />
+ <div className="h-full pb-4">
+ <HtmlPreviewBody
+ source={{ kind: "inline", html: text }}
+ title={state.filename}
+ className="h-full w-full"
+ iframeClassName="rounded-lg border-0"
+ />
+ </div>
)}
/>
);
@@ -900,17 +1017,46 @@ function PreviewContent({
attachmentId={state.attachmentId!}
onDownload={onDownload}
render={(text) => (
- <CodeBlockStatic
- language={extensionToLanguage(state.filename)}
- body={text}
- className="px-6 py-4"
- />
+ <DocumentSheet width="code" onBackdropClick={onBackdropClick}>
+ <CodeBlockStatic
+ language={extensionToLanguage(state.filename)}
+ body={text}
+ className="px-6 py-5"
+ />
+ </DocumentSheet>
)}
/>
);
}
}
+// A read-not-looked-at document: a centered sheet in the app's theme that
+// scrolls with the stage. Prose keeps a reading measure; code gets the room
+// long lines need. The scroll container spans the whole stage, so the wheel
+// works anywhere and its empty sides still count as backdrop.
+function DocumentSheet({
+ width,
+ onBackdropClick,
+ children,
+}: {
+ width: "prose" | "code";
+ onBackdropClick: (e: React.MouseEvent) => void;
+ children: ReactNode;
+}) {
+ return (
+ <div className="h-full overflow-y-auto" onClick={onBackdropClick}>
+ <div
+ className={cn(
+ "mx-auto min-h-full w-full rounded-t-lg bg-background text-foreground",
+ width === "prose" ? "max-w-3xl" : "max-w-5xl",
+ )}
+ >
+ {children}
+ </div>
+ </div>
+ );
+}
+
// ---------------------------------------------------------------------------
// Text-backed preview — fetches body once, then hands to the render prop
// ---------------------------------------------------------------------------
@@ -933,7 +1079,7 @@ function TextBackedPreview({
if (query.isLoading) {
return (
- <div className="flex h-full items-center justify-center gap-2 text-body text-muted-foreground">
+ <div className="dark flex h-full items-center justify-center gap-2 text-body text-muted-foreground">
<Loader2 className="size-4 animate-spin" />
{t(($) => $.attachment.preview_loading)}
</div>
@@ -968,7 +1114,7 @@ function TextBackedPreview({
}
// ---------------------------------------------------------------------------
-// Fallback — used for 413 / 415 / unknown kinds
+// Fallback — used for 413 / 415 / unknown kinds. Sits on the stage, so dark.
// ---------------------------------------------------------------------------
function UnsupportedFallback({
@@ -980,12 +1126,12 @@ function UnsupportedFallback({
}) {
const { t } = useT("editor");
return (
- <div className="flex h-full flex-col items-center justify-center gap-3 px-8 text-center">
+ <div className="dark flex h-full flex-col items-center justify-center gap-3 px-8 text-center">
<FileText className="size-8 text-muted-foreground" />
<p className="text-body text-muted-foreground">{message}</p>
<button
type="button"
- className="inline-flex items-center gap-2 rounded-md border border-border bg-background px-3 py-1.5 text-body transition-colors hover:bg-muted"
+ className="inline-flex items-center gap-2 rounded-md border border-input bg-secondary px-3 py-1.5 text-body text-foreground transition-colors hover:bg-muted"
onClick={onDownload}
>
<Download className="size-4" />
diff --git a/packages/views/editor/attachment.tsx b/packages/views/editor/attachment.tsx
index cfc2617985..ce3f174879 100644
--- a/packages/views/editor/attachment.tsx
+++ b/packages/views/editor/attachment.tsx
@@ -38,10 +38,10 @@ 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 { useImageSequencePreview } from "./image-sequence-context";
+import { usePreviewSequence } from "./preview-sequence-context";
import {
isObjectURL,
- useResignedInlineMediaURL,
+ useResignedInlineMedia,
} from "./hooks/use-inline-media-url";
import { useDownloadAttachment } from "./use-download-attachment";
import { AttachmentCard } from "./attachment-card";
@@ -323,7 +323,7 @@ export function Attachment({
const cdnSigned = useConfigStore((s) => s.cdnSigned);
const download = useDownloadAttachment();
const preview = useAttachmentPreview();
- const sequence = useImageSequencePreview();
+ const sequence = usePreviewSequence();
const state = normalize(attachment, resolveAttachment, cdnDomain, cdnSigned);
const forceKind =
@@ -339,7 +339,7 @@ export function Attachment({
// on deployments that have no signed URL to give — to an object URL built
// from the authenticated byte fetch. Only the image branch renders a native
// resource load, so only it opts into that byte fetch.
- const mediaUrl = useResignedInlineMediaURL(
+ const { url: mediaUrl } = useResignedInlineMedia(
state.attachmentId,
state.url,
kind === "image",
@@ -348,18 +348,18 @@ export function Attachment({
// to another surface keeps the durable pick instead.
const shareUrl = isObjectURL(mediaUrl) ? state.url : mediaUrl;
- // Identity this image has in the surrounding surface's sequence: the
+ // Identity this attachment has in the surrounding surface's sequence: the
// attachment id once the URL resolves to a record, otherwise the URL exactly
- // as written in the body — the same pair `collectImageSequence` keys on.
+ // as written in the body — the same pair `collectAttachmentSequence` keys on.
const sequenceKey =
state.attachmentId ?? (attachment.kind === "url" ? attachment.url : "");
const openPreview = () => {
- // Inside an issue / chat, an image opens the surface's shared viewer at
- // its real position so the reader can page through the rest. Anything the
+ // Inside an issue / chat, a file opens the surface's shared viewer at its
+ // real position so the reader can page through the rest. Anything the
// sequence doesn't know — a composer's in-flight upload, a surface with no
- // provider — falls through to the single-image preview below.
- if (kind === "image" && sequence.openAt(sequenceKey)) return;
+ // provider — falls through to the single-file preview below.
+ if (kind && sequence.openAt(sequenceKey)) return;
if (state.record) {
preview.tryOpen({
kind: "full",
diff --git a/packages/views/editor/hooks/use-inline-media-url.ts b/packages/views/editor/hooks/use-inline-media-url.ts
index d542f90c9f..5de84856ae 100644
--- a/packages/views/editor/hooks/use-inline-media-url.ts
+++ b/packages/views/editor/hooks/use-inline-media-url.ts
@@ -73,11 +73,16 @@ export function __resetInlineMediaBlobCacheForTests(): void {
// URL. `blobFallback` gates that on the caller actually rendering a native
// `<img>`: a file card only needs a link, and downloading a 100 MB archive
// into renderer memory to draw a chip would be a bad trade.
-export function useResignedInlineMediaURL(
+//
+// `pending` is true while that upgrade is still in flight — `url` is then the
+// picked URL, which this client may be unable to load. A caller that treats a
+// load failure as meaningful (the viewer skips broken images) waits it out
+// instead of rendering it.
+export function useResignedInlineMedia(
attachmentId: string | undefined,
pickedUrl: string,
blobFallback: boolean,
-): string {
+): { url: string; pending: boolean } {
const idFromPickedUrl = attachmentIdFromDownloadURL(pickedUrl);
const resignAttachmentId = attachmentId ?? idFromPickedUrl;
const isCrossOriginWebURL = (() => {
@@ -97,7 +102,7 @@ export function useResignedInlineMediaURL(
idFromPickedUrl !== undefined &&
((api.getBaseUrl?.() ?? "") !== "" || isCrossOriginWebURL);
- const { data: fresh } = useQuery({
+ const { data: fresh, isError: freshFailed } = useQuery({
queryKey: ["attachment-inline-resign", resignAttachmentId],
queryFn: () => api.getAttachment(resignAttachmentId as string),
enabled: needsResign,
@@ -117,7 +122,7 @@ export function useResignedInlineMediaURL(
// Only after `fresh` has landed do we know this deployment has nothing
// signed to give — firing the byte fetch earlier would double-download on
// every CloudFront / presign client.
- const { data: blob } = useQuery({
+ const { data: blob, isError: blobFailed } = useQuery({
queryKey: ["attachment-inline-blob", resignAttachmentId],
queryFn: () => api.getAttachmentBlob(resignAttachmentId as string),
enabled: needsResign && blobFallback && !!fresh && signedUrl === "",
@@ -127,8 +132,8 @@ export function useResignedInlineMediaURL(
const isAuthenticated = !!fresh;
const blobUrl = useObjectURL(resignAttachmentId, blob, isAuthenticated);
- if (!needsResign) return pickedUrl;
- if (signedUrl) return signedUrl;
+ if (!needsResign) return { url: pickedUrl, pending: false };
+ if (signedUrl) return { url: signedUrl, pending: false };
// Only return the cached blob URL when it belongs to the current id and
// the current QueryClient has authenticated metadata for it. This keeps
// the 5-min re-entry cache for the same session but prevents a logged-out
@@ -140,10 +145,16 @@ export function useResignedInlineMediaURL(
isAuthenticated &&
blobUrlCache.get(resignAttachmentId) === blobUrl
) {
- return blobUrl;
+ return { url: blobUrl, pending: false };
+ }
+ if (blobUrl && !resignAttachmentId && isAuthenticated) {
+ return { url: blobUrl, pending: false };
}
- if (blobUrl && !resignAttachmentId && isAuthenticated) return blobUrl;
- return pickedUrl;
+ // Still upgrading while the metadata is in flight, and — for a caller that
+ // renders the bytes — while they are. A failure at either step ends the
+ // wait on the picked URL.
+ const pending = !freshFailed && (!fresh || (blobFallback && !blobFailed));
+ return { url: pickedUrl, pending };
}
// useObjectURL turns a Blob into a `blob:` URL. The module cache keeps the
diff --git a/packages/views/editor/hooks/use-zoom-canvas.ts b/packages/views/editor/hooks/use-zoom-canvas.ts
index 04c6c3b996..4212a84950 100644
--- a/packages/views/editor/hooks/use-zoom-canvas.ts
+++ b/packages/views/editor/hooks/use-zoom-canvas.ts
@@ -129,7 +129,7 @@ export function useZoomCanvas({
// offsetWidth/offsetHeight, NOT getBoundingClientRect: both viewers open
// inside a container that scales in (`zoom-in-95` on the shared Dialog,
- // motion's scale(0.95) on the attachment modal). A client rect is
+ // motion's scale-in on the attachment viewer's stage). A client rect is
// transform-scaled, so measuring mid-animation would fit the content
// against a viewport a few percent too small — and because ResizeObserver
// reports the untransformed layout box, it never fires when the animation
diff --git a/packages/views/editor/index.ts b/packages/views/editor/index.ts
index bc912837ee..c97b1daaba 100644
--- a/packages/views/editor/index.ts
+++ b/packages/views/editor/index.ts
@@ -33,9 +33,10 @@ export type {
PreviewSequence,
} from "./attachment-preview-modal";
export {
- ImageSequenceProvider,
- useImageSequencePreview,
-} from "./image-sequence-context";
+ PreviewSequenceProvider,
+ collectPreviewSequence,
+ usePreviewSequence,
+} from "./preview-sequence-context";
export { AttachmentCard } from "./attachment-card";
export type { AttachmentCardProps } from "./attachment-card";
export { Attachment } from "./attachment";
diff --git a/packages/views/editor/image-sequence-context.test.tsx b/packages/views/editor/preview-sequence-context.test.tsx
similarity index 63%
rename from packages/views/editor/image-sequence-context.test.tsx
rename to packages/views/editor/preview-sequence-context.test.tsx
index ea311d433a..7f862878b7 100644
--- a/packages/views/editor/image-sequence-context.test.tsx
+++ b/packages/views/editor/preview-sequence-context.test.tsx
@@ -8,7 +8,6 @@ import {
import { QueryClient, QueryClientProvider } from "@tanstack/react-query";
import { useState, type ReactElement } from "react";
import type { Attachment } from "@multica/core/types";
-import { collectImageSequence } from "@multica/core/attachments/image-sequence";
const { downloadMock, getBaseUrlMock, toastErrorMock } = vi.hoisted(() => ({
downloadMock: vi.fn(),
@@ -52,9 +51,6 @@ const STRINGS: Record<string, Record<string, string>> = {
view: "View",
copy_link: "Copy link",
canvas_label: "Image canvas",
- previous: "Previous image",
- next: "Next image",
- sequence_position: "{{index}} / {{total}}",
unavailable: "That image is no longer available — skipped it.",
},
canvas: {
@@ -67,6 +63,9 @@ const STRINGS: Record<string, Record<string, string>> = {
close: "Close",
preview_unsupported: "This file type can't be previewed.",
open_in_new_tab: "Open in new tab",
+ previous: "Previous",
+ next: "Next",
+ sequence_position: "{{index}} / {{total}}",
},
};
@@ -84,9 +83,10 @@ vi.mock("../i18n", () => ({
}));
import {
- ImageSequenceProvider,
- useImageSequencePreview,
-} from "./image-sequence-context";
+ PreviewSequenceProvider,
+ collectPreviewSequence,
+ usePreviewSequence,
+} from "./preview-sequence-context";
import { Attachment as InlineAttachment } from "./attachment";
import { AttachmentDownloadProvider } from "./attachment-download-context";
@@ -124,13 +124,30 @@ function imageAttachment(n: number): Attachment {
const THREE = [imageAttachment(1), imageAttachment(2), imageAttachment(3)];
// Each attachment lands in its own block, mirroring three comments each
-// carrying one screenshot.
+// carrying one file.
function sequenceOf(attachments: Attachment[]) {
- return collectImageSequence(attachments.map((a) => ({ attachments: [a] })));
+ return collectPreviewSequence(attachments.map((a) => ({ attachments: [a] })));
+}
+
+// jsdom has no Image.decode(); the viewer swaps images without one, so the
+// decode-then-swap path only runs under a stub. Returns the restore.
+function stubDecode(impl: (this: HTMLImageElement) => Promise<void>): () => void {
+ Object.defineProperty(HTMLImageElement.prototype, "decode", {
+ configurable: true,
+ writable: true,
+ value: impl,
+ });
+ return () => {
+ delete (HTMLImageElement.prototype as { decode?: unknown }).decode;
+ };
+}
+
+function fileAttachment(n: number, filename: string, contentType: string): Attachment {
+ return { ...imageAttachment(n), filename, content_type: contentType };
}
function Opener({ openKey }: { openKey: string }) {
- const sequence = useImageSequencePreview();
+ const sequence = usePreviewSequence();
return (
<button type="button" onClick={() => sequence.openAt(openKey)}>
open
@@ -144,22 +161,22 @@ function expectCounter(text: string) {
}
function prevButton(): HTMLButtonElement {
- return screen.getByRole("button", { name: "Previous image" });
+ return screen.getByRole("button", { name: "Previous" });
}
function nextButton(): HTMLButtonElement {
- return screen.getByRole("button", { name: "Next image" });
+ return screen.getByRole("button", { name: "Next" });
}
beforeEach(() => {
vi.clearAllMocks();
});
-describe("ImageSequenceProvider", () => {
+describe("PreviewSequenceProvider", () => {
it("opens at the clicked image's real position and reports X / Y", () => {
render(
- <ImageSequenceProvider items={sequenceOf(THREE)}>
+ <PreviewSequenceProvider items={sequenceOf(THREE)}>
<Opener openKey={THREE[1]!.id} />
- </ImageSequenceProvider>,
+ </PreviewSequenceProvider>,
);
act(() => {
@@ -175,9 +192,9 @@ describe("ImageSequenceProvider", () => {
it("walks forward and back without wrapping, disabling at each end", () => {
render(
- <ImageSequenceProvider items={sequenceOf(THREE)}>
+ <PreviewSequenceProvider items={sequenceOf(THREE)}>
<Opener openKey={THREE[0]!.id} />
- </ImageSequenceProvider>,
+ </PreviewSequenceProvider>,
);
act(() => {
fireEvent.click(screen.getByText("open"));
@@ -209,9 +226,9 @@ describe("ImageSequenceProvider", () => {
it("moves with the left / right arrow keys", () => {
render(
- <ImageSequenceProvider items={sequenceOf(THREE)}>
+ <PreviewSequenceProvider items={sequenceOf(THREE)}>
<Opener openKey={THREE[0]!.id} />
- </ImageSequenceProvider>,
+ </PreviewSequenceProvider>,
);
act(() => {
fireEvent.click(screen.getByText("open"));
@@ -238,7 +255,7 @@ describe("ImageSequenceProvider", () => {
function Harness() {
const [items, setItems] = useState(sequenceOf(THREE));
return (
- <ImageSequenceProvider items={items}>
+ <PreviewSequenceProvider items={items}>
<Opener openKey={THREE[2]!.id} />
<button
type="button"
@@ -248,7 +265,7 @@ describe("ImageSequenceProvider", () => {
>
grow
</button>
- </ImageSequenceProvider>
+ </PreviewSequenceProvider>
);
}
render(<Harness />);
@@ -267,9 +284,9 @@ describe("ImageSequenceProvider", () => {
it("skips a broken image and says so", () => {
render(
- <ImageSequenceProvider items={sequenceOf(THREE)}>
+ <PreviewSequenceProvider items={sequenceOf(THREE)}>
<Opener openKey={THREE[0]!.id} />
- </ImageSequenceProvider>,
+ </PreviewSequenceProvider>,
);
act(() => {
fireEvent.click(screen.getByText("open"));
@@ -293,10 +310,132 @@ describe("ImageSequenceProvider", () => {
expectCounter("1 / 3");
});
+ it("pages onto files that are not images", () => {
+ const mixed = [
+ imageAttachment(1),
+ fileAttachment(2, "spec.pdf", "application/pdf"),
+ imageAttachment(3),
+ ];
+ render(
+ <PreviewSequenceProvider items={sequenceOf(mixed)}>
+ <Opener openKey={mixed[0]!.id} />
+ </PreviewSequenceProvider>,
+ );
+ act(() => {
+ fireEvent.click(screen.getByText("open"));
+ });
+
+ act(() => {
+ fireEvent.click(nextButton());
+ });
+ expectCounter("2 / 3");
+ expect(screen.getByTitle("spec.pdf").tagName).toBe("IFRAME");
+
+ act(() => {
+ fireEvent.click(nextButton());
+ });
+ expectCounter("3 / 3");
+ expect(screen.getByRole("dialog").querySelector("img")).not.toBeNull();
+ });
+
+ it("leaves the arrow keys to a focused video", () => {
+ const mixed = [
+ fileAttachment(1, "demo.mp4", "video/mp4"),
+ imageAttachment(2),
+ ];
+ render(
+ <PreviewSequenceProvider items={sequenceOf(mixed)}>
+ <Opener openKey={mixed[0]!.id} />
+ </PreviewSequenceProvider>,
+ );
+ act(() => {
+ fireEvent.click(screen.getByText("open"));
+ });
+
+ const video = screen.getByRole("dialog").querySelector("video")!;
+ act(() => {
+ fireEvent.keyDown(video, { key: "ArrowRight" });
+ });
+ // The player seeks; the viewer stays put.
+ expectCounter("1 / 2");
+
+ act(() => {
+ fireEvent.keyDown(document, { key: "ArrowRight" });
+ });
+ expectCounter("2 / 2");
+ });
+
+ // Review of #8763: the panel is reused across kinds, so the frame it held
+ // for a PDF must never reach the image canvas while the next image decodes.
+ it("shows the image itself, not the previous file, while it decodes", () => {
+ const restoreDecode = stubDecode(() => new Promise<void>(() => {}));
+ try {
+ const mixed = [
+ fileAttachment(1, "spec.pdf", "application/pdf"),
+ imageAttachment(2),
+ imageAttachment(3),
+ ];
+ render(
+ <PreviewSequenceProvider items={sequenceOf(mixed)}>
+ <Opener openKey={mixed[0]!.id} />
+ </PreviewSequenceProvider>,
+ );
+ act(() => {
+ fireEvent.click(screen.getByText("open"));
+ });
+ act(() => {
+ fireEvent.click(nextButton());
+ });
+
+ const image = screen.getByRole("dialog").querySelector("img")!;
+ expect(image.getAttribute("src")).toBe(mixed[1]!.download_url);
+ expectCounter("2 / 3");
+ expect(nextButton()).not.toBeDisabled();
+ expect(toastErrorMock).not.toHaveBeenCalled();
+ } finally {
+ restoreDecode();
+ }
+ });
+
+ it("does not blame the next image for an error on the frame still held", async () => {
+ const [first, second] = [imageAttachment(1), imageAttachment(2)];
+ const restoreDecode = stubDecode(function (this: HTMLImageElement) {
+ return this.src === first.download_url
+ ? Promise.resolve()
+ : new Promise<void>(() => {});
+ });
+ try {
+ render(
+ <PreviewSequenceProvider items={sequenceOf([first, second])}>
+ <Opener openKey={first.id} />
+ </PreviewSequenceProvider>,
+ );
+ act(() => {
+ fireEvent.click(screen.getByText("open"));
+ });
+ await act(async () => {});
+ act(() => {
+ fireEvent.click(nextButton());
+ });
+
+ // The first image stays up while the second decodes; an error from it
+ // is about the first file, not the one being opened.
+ const held = screen.getByRole("dialog").querySelector("img")!;
+ expect(held.getAttribute("src")).toBe(first.download_url);
+ act(() => {
+ fireEvent.error(held);
+ });
+ expectCounter("2 / 2");
+ expect(toastErrorMock).not.toHaveBeenCalled();
+ } finally {
+ restoreDecode();
+ }
+ });
+
it("reports false for an image the surface does not know", () => {
const seen: boolean[] = [];
function Probe() {
- const sequence = useImageSequencePreview();
+ const sequence = usePreviewSequence();
return (
<button
type="button"
@@ -307,9 +446,9 @@ describe("ImageSequenceProvider", () => {
);
}
render(
- <ImageSequenceProvider items={sequenceOf(THREE)}>
+ <PreviewSequenceProvider items={sequenceOf(THREE)}>
<Probe />
- </ImageSequenceProvider>,
+ </PreviewSequenceProvider>,
);
act(() => {
fireEvent.click(screen.getByText("try"));
@@ -320,15 +459,15 @@ describe("ImageSequenceProvider", () => {
it("leaves a lone image with no sequence chrome", () => {
render(
- <ImageSequenceProvider items={sequenceOf([THREE[0]!])}>
+ <PreviewSequenceProvider items={sequenceOf([THREE[0]!])}>
<Opener openKey={THREE[0]!.id} />
- </ImageSequenceProvider>,
+ </PreviewSequenceProvider>,
);
act(() => {
fireEvent.click(screen.getByText("open"));
});
expect(screen.getByRole("dialog")).toBeInTheDocument();
- expect(screen.queryByRole("button", { name: "Next image" })).toBeNull();
+ expect(screen.queryByRole("button", { name: "Next" })).toBeNull();
});
});
@@ -344,8 +483,8 @@ describe("body images with no attachment record", () => {
.join("\n\n");
return (
<AttachmentDownloadProvider attachments={[]}>
- <ImageSequenceProvider
- items={collectImageSequence([{ content, attachments: [] }])}
+ <PreviewSequenceProvider
+ items={collectPreviewSequence([{ content, attachments: [] }])}
>
{captions.map((caption, i) => (
<InlineAttachment
@@ -358,7 +497,7 @@ describe("body images with no attachment record", () => {
}}
/>
))}
- </ImageSequenceProvider>
+ </PreviewSequenceProvider>
</AttachmentDownloadProvider>
);
}
@@ -395,11 +534,11 @@ describe("body images with no attachment record", () => {
});
});
-describe("useImageSequencePreview without a provider", () => {
+describe("usePreviewSequence without a provider", () => {
it("reports false so the caller can fall back to a single preview", () => {
const seen: boolean[] = [];
function Probe() {
- const sequence = useImageSequencePreview();
+ const sequence = usePreviewSequence();
return (
<button type="button" onClick={() => seen.push(sequence.openAt("k"))}>
try
diff --git a/packages/views/editor/image-sequence-context.tsx b/packages/views/editor/preview-sequence-context.tsx
similarity index 61%
rename from packages/views/editor/image-sequence-context.tsx
rename to packages/views/editor/preview-sequence-context.tsx
index e61bd52888..9f4c94dcdc 100644
--- a/packages/views/editor/image-sequence-context.tsx
+++ b/packages/views/editor/preview-sequence-context.tsx
@@ -1,30 +1,32 @@
"use client";
/**
- * ImageSequenceProvider — prev / next for the images of ONE surface (MUL-5752).
+ * PreviewSequenceProvider — prev / next for the attachments of ONE surface
+ * (MUL-5752, MUL-7642).
*
- * A surface that can hold several images (an issue: description + every
+ * A surface that can hold several attachments (an issue: description + every
* comment; a chat session: every message) mounts this once with the ordered
- * sequence built by `collectImageSequence`. Clicking any image inside opens
- * the shared preview modal at that image's real position and lets the reader
- * page through the rest.
+ * sequence built by `collectPreviewSequence`. Opening any previewable
+ * attachment inside — an image, a PDF, a Markdown report, an HTML file —
+ * opens the shared viewer at its real position so the reader can page through
+ * the rest of the surface's files.
*
- * Why one provider instead of per-image state: `<Attachment>` owns a private
- * `useAttachmentPreview()` modal, which is right for a lone image but cannot
- * know what comes next. The provider hosts a single modal above every image,
- * so navigation state has exactly one owner.
+ * Why one provider instead of per-attachment state: `<Attachment>` owns a
+ * private `useAttachmentPreview()` modal, which is right for a lone file but
+ * cannot know what comes next. The provider hosts a single modal above every
+ * attachment, so navigation state has exactly one owner.
*
* Two behaviours worth stating up front, both from the product brief:
*
* - The sequence is FROZEN when the modal opens. New comments and streaming
* agent output keep arriving while a preview is open; recomputing live
* would shift "3 / 7" under the reader mid-look.
- * - Boundaries DISABLE, they don't wrap. First image: no previous. Last
- * image: no next.
+ * - Boundaries DISABLE, they don't wrap. First file: no previous. Last
+ * file: no next.
*
- * Images outside the sequence (an in-flight upload in a composer, an image in
- * a surface with no provider) are not an error: `openAt` reports false and the
- * caller falls back to its own single-image preview.
+ * Attachments outside the sequence (an in-flight upload in a composer, a file
+ * in a surface with no provider) are not an error: `openAt` reports false and
+ * the caller falls back to its own single-file preview.
*/
import {
@@ -38,7 +40,9 @@ import {
} from "react";
import { toast } from "sonner";
import {
+ collectAttachmentSequence,
indexOfImageKey,
+ type ImageSequenceBlock,
type ImageSequenceItem,
} from "@multica/core/attachments/image-sequence";
import { useT } from "../i18n";
@@ -47,46 +51,61 @@ import {
PreviewImagePrefetch,
type PreviewSource,
} from "./attachment-preview-modal";
+import { canOpenPreview, getPreviewKind } from "./utils/preview";
-interface ImageSequenceApi {
+/**
+ * The sequence a web / desktop surface pages through: every attachment the
+ * viewer can open, in render order.
+ */
+export function collectPreviewSequence(
+ blocks: ReadonlyArray<ImageSequenceBlock | null | undefined>,
+): ImageSequenceItem[] {
+ return collectAttachmentSequence(blocks, ({ contentType, filename, hasRecord }) =>
+ canOpenPreview(getPreviewKind(contentType, filename), hasRecord),
+ );
+}
+
+interface PreviewSequenceApi {
/**
* Open the shared viewer at `key` — the attachment id, or the URL as written
* in the body for references that don't resolve to a record.
*
* Returns false when no provider is mounted or the key is not part of this
- * surface's sequence, so callers can fall back to a single-image preview.
+ * surface's sequence, so callers can fall back to a single-file preview.
*/
openAt: (key: string) => boolean;
}
-const NO_SEQUENCE: ImageSequenceApi = { openAt: () => false };
+const NO_SEQUENCE: PreviewSequenceApi = { openAt: () => false };
-const ImageSequenceContext = createContext<ImageSequenceApi>(NO_SEQUENCE);
+const PreviewSequenceContext = createContext<PreviewSequenceApi>(NO_SEQUENCE);
/**
- * Returns the surrounding surface's image viewer, or a no-op handle when
- * there is no provider. Always safe to call — `openAt` reporting false is the
+ * Returns the surrounding surface's viewer, or a no-op handle when there is
+ * no provider. Always safe to call — `openAt` reporting false is the
* documented "not part of a sequence" answer, not a failure.
*/
-export function useImageSequencePreview(): ImageSequenceApi {
- return use(ImageSequenceContext);
+export function usePreviewSequence(): PreviewSequenceApi {
+ return use(PreviewSequenceContext);
}
function toPreviewSource(item: ImageSequenceItem): PreviewSource {
- return item.attachment
- ? { kind: "full", attachment: item.attachment }
- : // Everything in a sequence is an image by construction —
- // `collectImageSequence` admits nothing else — so the viewer says so
- // rather than letting the modal re-derive it from `filename`. For an
- // item with no attachment record that field holds the markdown caption
- // (`![报告图表](…)`), which is prose and has no extension to read
- // (MUL-7518).
- {
- kind: "url",
- url: item.url,
- filename: item.filename,
- forceKind: "image",
- };
+ if (item.attachment) return { kind: "full", attachment: item.attachment };
+ return {
+ kind: "url",
+ url: item.url,
+ filename: item.filename,
+ // A body image's `filename` is its markdown caption — prose with no
+ // extension to read — so say what it is instead of letting the modal
+ // re-derive it (MUL-7518). A file card's name is a real filename.
+ forceKind: item.imageByConstruction ? "image" : undefined,
+ };
+}
+
+function isImageItem(item: ImageSequenceItem): boolean {
+ if (item.imageByConstruction) return true;
+ const contentType = item.attachment?.content_type ?? "";
+ return getPreviewKind(contentType, item.filename || item.url) === "image";
}
interface Session {
@@ -95,7 +114,7 @@ interface Session {
index: number;
}
-export function ImageSequenceProvider({
+export function PreviewSequenceProvider({
items,
children,
}: {
@@ -111,7 +130,7 @@ export function ImageSequenceProvider({
const [session, setSession] = useState<Session | null>(null);
const [open, setOpen] = useState(false);
// Images that failed to load this session. Kept out of navigation so a
- // deleted attachment can't trap the reader on a broken frame, and so the
+ // deleted image can't trap the reader on a broken frame, and so the
// auto-skip below can't bounce between two dead images forever. The ref is
// the synchronous truth (an <img> can report failure more than once before
// React re-renders); the state copy exists to drive that re-render.
@@ -121,7 +140,7 @@ export function ImageSequenceProvider({
// reader was already going.
const directionRef = useRef<1 | -1>(1);
- const api = useMemo<ImageSequenceApi>(
+ const api = useMemo<PreviewSequenceApi>(
() => ({
openAt: (key: string) => {
const snapshot = [...itemsRef.current];
@@ -207,24 +226,26 @@ export function ImageSequenceProvider({
) : null;
return (
- <ImageSequenceContext.Provider value={api}>
+ <PreviewSequenceContext.Provider value={api}>
{children}
{modal}
- {/* Warm the immediate neighbours while a preview is open, so paging
- swaps from cache instead of waiting a network round-trip. Keyed
- mounts: moving re-targets the prefetch to the new neighbours. */}
- {open && session && prevIndex >= 0 && (
+ {/* Warm the immediate image neighbours while a preview is open, so
+ paging swaps from cache instead of waiting a network round-trip.
+ Other kinds load on arrival — a PDF or a video is not worth
+ fetching speculatively. Keyed mounts: moving re-targets the
+ prefetch to the new neighbours. */}
+ {open && session && prevIndex >= 0 && isImageItem(session.items[prevIndex]!) && (
<PreviewImagePrefetch
key={session.items[prevIndex]!.key}
source={toPreviewSource(session.items[prevIndex]!)}
/>
)}
- {open && session && nextIndex >= 0 && (
+ {open && session && nextIndex >= 0 && isImageItem(session.items[nextIndex]!) && (
<PreviewImagePrefetch
key={session.items[nextIndex]!.key}
source={toPreviewSource(session.items[nextIndex]!)}
/>
)}
- </ImageSequenceContext.Provider>
+ </PreviewSequenceContext.Provider>
);
}
diff --git a/packages/views/editor/styles/zoom-canvas.css b/packages/views/editor/styles/zoom-canvas.css
index a3397aea56..a550917ebe 100644
--- a/packages/views/editor/styles/zoom-canvas.css
+++ b/packages/views/editor/styles/zoom-canvas.css
@@ -33,6 +33,14 @@
outline-offset: -2px;
}
+/* Focus the canvas placed on itself when it opened (`autoFocus`) is for the
+ keyboard controls; it can still match :focus-visible, which drew the ring
+ around the whole stage of the full-window viewer. No ring until focus has
+ left once — tabbing back in shows it as usual. */
+.zoom-canvas[data-autofocused]:focus-visible {
+ outline: none;
+}
+
.zoom-canvas.is-panning {
cursor: grabbing;
}
diff --git a/packages/views/editor/utils/preview.ts b/packages/views/editor/utils/preview.ts
index e43720e5ee..bda8954e47 100644
--- a/packages/views/editor/utils/preview.ts
+++ b/packages/views/editor/utils/preview.ts
@@ -199,10 +199,33 @@ export function getPreviewKind(
return null;
}
+/** Short type label for metadata lines — the extension, upper-cased (`PNG`). */
+export function fileTypeLabel(filename: string): string {
+ return extOf(filename).toUpperCase();
+}
+
export function isPreviewable(contentType: string, filename: string): boolean {
return getPreviewKind(contentType, filename) !== null;
}
+// Kinds that render straight from a URL. Text kinds (markdown / html / text)
+// go through the ID-keyed `/api/attachments/{id}/content` proxy, so they can
+// only open when the attachment record is known.
+const URL_PREVIEWABLE_KINDS: ReadonlySet<PreviewKind> = new Set<PreviewKind>([
+ "image",
+ "pdf",
+ "video",
+ "audio",
+]);
+
+/** Whether the viewer can open `kind`, given whether the record is known. */
+export function canOpenPreview(
+ kind: PreviewKind | null,
+ hasRecord: boolean,
+): kind is PreviewKind {
+ return kind !== null && (hasRecord || URL_PREVIEWABLE_KINDS.has(kind));
+}
+
// Pick the hljs language token for a file. Returns undefined when the file
// doesn't have a recognizable extension — callers can fall back to a plain
// `<pre>` render. Kept tiny and ext-driven on purpose: lowlight's `common`
diff --git a/packages/views/editor/zoom-canvas.tsx b/packages/views/editor/zoom-canvas.tsx
index 2e8dccdcb7..268d6f00b3 100644
--- a/packages/views/editor/zoom-canvas.tsx
+++ b/packages/views/editor/zoom-canvas.tsx
@@ -156,7 +156,14 @@ export function ZoomCanvas({
(node: HTMLDivElement | null) => {
if (canvasRef) canvasRef.current = node;
canvas.setViewportNode(node);
- if (node && autoFocus) node.focus({ preventScroll: true });
+ if (node && autoFocus) {
+ // This focus is for the keyboard controls, not a reader tabbing in —
+ // marked so the stylesheet drops the ring until focus leaves (see
+ // zoom-canvas.css). On a full-window surface the ring framed the
+ // whole stage.
+ node.dataset.autofocused = "";
+ node.focus({ preventScroll: true });
+ }
},
[canvasRef, canvas.setViewportNode, autoFocus],
);
@@ -176,6 +183,9 @@ export function ZoomCanvas({
onPointerCancel={canvas.handlePointerUp}
onDoubleClick={canvas.handleDoubleClick}
onKeyDown={canvas.handleKeyDown}
+ onBlur={(e) => {
+ delete e.currentTarget.dataset.autofocused;
+ }}
>
<div
className={cn(
diff --git a/packages/views/issues/components/issue-detail.test.tsx b/packages/views/issues/components/issue-detail.test.tsx
index dbf446630b..3c8c703698 100644
--- a/packages/views/issues/components/issue-detail.test.tsx
+++ b/packages/views/issues/components/issue-detail.test.tsx
@@ -164,11 +164,12 @@ vi.mock("../../editor", async () => ({
tryOpen: () => false,
modal: null,
}),
- // Pass-through: the detail page wraps its column in the image-sequence
- // provider, but paging between images is covered in
- // image-sequence-context.test.tsx against the real provider.
- ImageSequenceProvider: ({ children }: { children: React.ReactNode }) =>
+ // Pass-through: the detail page wraps its column in the preview-sequence
+ // provider, but paging between files is covered in
+ // preview-sequence-context.test.tsx against the real provider.
+ PreviewSequenceProvider: ({ children }: { children: React.ReactNode }) =>
children,
+ collectPreviewSequence: () => [],
isPreviewable: () => false,
ReadonlyContent: ({ content }: { content: string }) => {
readonlyContentRenders.push(content);
diff --git a/packages/views/issues/components/issue-detail.tsx b/packages/views/issues/components/issue-detail.tsx
index 10cf54d6e9..0ed4ce85f2 100644
--- a/packages/views/issues/components/issue-detail.tsx
+++ b/packages/views/issues/components/issue-detail.tsx
@@ -39,8 +39,8 @@ import { Button } from "@multica/ui/components/ui/button";
import { ResizablePanelGroup, ResizablePanel, ResizableHandle } from "@multica/ui/components/ui/resizable";
import { Sheet, SheetContent } from "@multica/ui/components/ui/sheet";
import { useIsMobile } from "@multica/ui/hooks/use-mobile";
-import { ContentEditor, type ContentEditorRef, TitleEditor, type TitleEditorRef, useFileDropZone, FileDropOverlay, useLazyEditor, useEditorUpload, ImageSequenceProvider } from "../../editor";
-import { collectImageSequence, type ImageSequenceBlock } from "@multica/core/attachments/image-sequence";
+import { ContentEditor, type ContentEditorRef, TitleEditor, type TitleEditorRef, useFileDropZone, FileDropOverlay, useLazyEditor, useEditorUpload, PreviewSequenceProvider, collectPreviewSequence } from "../../editor";
+import type { ImageSequenceBlock } from "@multica/core/attachments/image-sequence";
import { FileUploadButton } from "@multica/ui/components/common/file-upload-button";
import {
Tooltip,
@@ -2158,19 +2158,28 @@ export function IssueDetail({ issueId, onDelete, onDone, defaultSidebarOpen = tr
[issueAttachments, descPendingAttachments],
);
- // Every image in this issue, in the order the page renders them: the
- // description first, then each timeline comment with its thread replies
+ // Every previewable file in this issue, in the order the page renders them:
+ // the description first, then each timeline comment with its thread replies
// nested under it (MUL-5752). Built from `items` rather than the flat
// timeline so a reply sits next to the root it renders under, and from data
// rather than the DOM because Virtuoso only mounts the visible window.
//
// A resolved thread that is currently collapsed still contributes its
- // images: they belong to the issue and are one click from being on screen,
+ // files: they belong to the issue and are one click from being on screen,
// so leaving them out would make the counter change depending on which
// threads happen to be folded.
- const imageSequence = useMemo(() => {
+ //
+ // The description renders no standalone cards, and its attachment list is
+ // the whole issue's (comment uploads keep `issue_id`) — it only resolves the
+ // description's own references, or every comment file would be counted at
+ // the description's position.
+ const previewSequence = useMemo(() => {
const blocks: ImageSequenceBlock[] = [
- { content: issue?.description, attachments: descEditorAttachments },
+ {
+ content: issue?.description,
+ attachments: descEditorAttachments,
+ standalone: false,
+ },
];
for (const item of items) {
if (item.kind === "activity-group" || !item.entry) continue;
@@ -2182,7 +2191,7 @@ export function IssueDetail({ issueId, onDelete, onDone, defaultSidebarOpen = tr
blocks.push({ content: reply.content, attachments: reply.attachments });
}
}
- return collectImageSequence(blocks);
+ return collectPreviewSequence(blocks);
}, [issue?.description, descEditorAttachments, items, timelineView.threadReplies]);
const handleDescriptionUpload = useCallback(
@@ -2873,11 +2882,11 @@ export function IssueDetail({ issueId, onDelete, onDone, defaultSidebarOpen = tr
: [];
const detailContent = (
- // Hosts the one image viewer this issue's images page through — see
- // ImageSequenceProvider. Wraps the whole column so the description
- // editor's images and the timeline's images share one sequence.
+ // Hosts the one viewer this issue's files page through — see
+ // PreviewSequenceProvider. Wraps the whole column so the description
+ // editor's files and the timeline's files share one sequence.
<CurrentIssueRenderContextProvider value={currentIssueRenderContext}>
- <ImageSequenceProvider items={imageSequence}>
+ <PreviewSequenceProvider items={previewSequence}>
<div className="relative flex h-full min-w-0 flex-1 flex-col">
{/* In-page find bar — floats over the top-right of the content column
(below the breadcrumb header), outside the scroll container so it
@@ -3626,7 +3635,7 @@ export function IssueDetail({ issueId, onDelete, onDone, defaultSidebarOpen = tr
/>
)}
</div>
- </ImageSequenceProvider>
+ </PreviewSequenceProvider>
</CurrentIssueRenderContextProvider>
);
diff --git a/packages/views/locales/en/editor.json b/packages/views/locales/en/editor.json
index be99fe7474..a9d2841c55 100644
--- a/packages/views/locales/en/editor.json
+++ b/packages/views/locales/en/editor.json
@@ -41,9 +41,6 @@
"link_copied": "Link copied",
"copy_link_failed": "Failed to copy link",
"canvas_label": "Image canvas. Drag to pan, scroll to zoom, double-click to toggle actual size.",
- "previous": "Previous image",
- "next": "Next image",
- "sequence_position": "{{index}} / {{total}}",
"unavailable": "That image is no longer available — skipped it."
},
"canvas": {
@@ -61,7 +58,10 @@
"preview_unsupported": "This file type can't be previewed.",
"close": "Close",
"open_in_new_tab": "Open in new tab",
- "remove": "Remove attachment"
+ "remove": "Remove attachment",
+ "previous": "Previous",
+ "next": "Next",
+ "sequence_position": "{{index}} / {{total}}"
},
"link_hover": {
"copy_link": "Copy link",
diff --git a/packages/views/locales/fr/editor.json b/packages/views/locales/fr/editor.json
index b5737125da..0e3de3ac5a 100644
--- a/packages/views/locales/fr/editor.json
+++ b/packages/views/locales/fr/editor.json
@@ -41,9 +41,6 @@
"link_copied": "Lien copié",
"copy_link_failed": "Échec de la copie du lien",
"canvas_label": "Zone d'image. Faites glisser pour déplacer, faites défiler pour zoomer, double-cliquez pour basculer en taille réelle.",
- "previous": "Image précédente",
- "next": "Image suivante",
- "sequence_position": "{{index}} / {{total}}",
"unavailable": "Cette image n'est plus disponible — elle a été ignorée."
},
"canvas": {
@@ -61,7 +58,10 @@
"preview_unsupported": "Ce type de fichier ne peut pas être prévisualisé.",
"close": "Fermer",
"open_in_new_tab": "Ouvrir dans un nouvel onglet",
- "remove": "Supprimer la pièce jointe"
+ "remove": "Supprimer la pièce jointe",
+ "previous": "Précédent",
+ "next": "Suivant",
+ "sequence_position": "{{index}} / {{total}}"
},
"link_hover": {
"copy_link": "Copier le lien",
diff --git a/packages/views/locales/ja/editor.json b/packages/views/locales/ja/editor.json
index 8b77522507..f6ac5dd798 100644
--- a/packages/views/locales/ja/editor.json
+++ b/packages/views/locales/ja/editor.json
@@ -41,9 +41,6 @@
"link_copied": "リンクをコピーしました",
"copy_link_failed": "リンクをコピーできませんでした",
"canvas_label": "画像キャンバス。ドラッグで移動、スクロールで拡大縮小、ダブルクリックで実際のサイズに切り替えできます。",
- "previous": "前の画像",
- "next": "次の画像",
- "sequence_position": "{{index}} / {{total}}",
"unavailable": "この画像は表示できないためスキップしました。"
},
"canvas": {
@@ -61,7 +58,10 @@
"preview_unsupported": "このファイル形式はプレビューできません。",
"close": "閉じる",
"open_in_new_tab": "新しいタブで開く",
- "remove": "添付ファイルを削除"
+ "remove": "添付ファイルを削除",
+ "previous": "前へ",
+ "next": "次へ",
+ "sequence_position": "{{index}} / {{total}}"
},
"link_hover": {
"copy_link": "リンクをコピー",
diff --git a/packages/views/locales/ko/editor.json b/packages/views/locales/ko/editor.json
index e6e71360cc..cdb89e340d 100644
--- a/packages/views/locales/ko/editor.json
+++ b/packages/views/locales/ko/editor.json
@@ -41,9 +41,6 @@
"link_copied": "링크를 복사했습니다",
"copy_link_failed": "링크를 복사하지 못했습니다",
"canvas_label": "이미지 캔버스. 드래그하여 이동, 스크롤하여 확대/축소, 두 번 클릭하여 실제 크기로 전환할 수 있습니다.",
- "previous": "이전 이미지",
- "next": "다음 이미지",
- "sequence_position": "{{index}} / {{total}}",
"unavailable": "이 이미지를 불러올 수 없어 건너뛰었습니다."
},
"canvas": {
@@ -61,7 +58,10 @@
"preview_unsupported": "이 파일 형식은 미리보기를 지원하지 않습니다.",
"close": "닫기",
"open_in_new_tab": "새 탭에서 열기",
- "remove": "첨부 파일 제거"
+ "remove": "첨부 파일 제거",
+ "previous": "이전",
+ "next": "다음",
+ "sequence_position": "{{index}} / {{total}}"
},
"link_hover": {
"copy_link": "링크 복사",
diff --git a/packages/views/locales/zh-Hans/editor.json b/packages/views/locales/zh-Hans/editor.json
index e6a965d58e..5d10fb31a9 100644
--- a/packages/views/locales/zh-Hans/editor.json
+++ b/packages/views/locales/zh-Hans/editor.json
@@ -41,9 +41,6 @@
"link_copied": "已复制链接",
"copy_link_failed": "复制链接失败",
"canvas_label": "图片画布,拖动可平移,滚动可缩放,双击可切换实际大小。",
- "previous": "上一张",
- "next": "下一张",
- "sequence_position": "第 {{index}} / {{total}} 张",
"unavailable": "这张图片已失效,已跳过。"
},
"canvas": {
@@ -61,7 +58,10 @@
"preview_unsupported": "该文件类型暂不支持预览。",
"close": "关闭",
"open_in_new_tab": "在新标签页打开",
- "remove": "移除附件"
+ "remove": "移除附件",
+ "previous": "上一个",
+ "next": "下一个",
+ "sequence_position": "{{index}} / {{total}}"
},
"link_hover": {
"copy_link": "复制链接",