diff --git a/packages/app/e2e/regression/review.spec.ts b/packages/app/e2e/regression/review.spec.ts index b6002a3ea4d..a9e50668a6c 100644 --- a/packages/app/e2e/regression/review.spec.ts +++ b/packages/app/e2e/regression/review.spec.ts @@ -6,6 +6,7 @@ import { browseFiles, openFileLauncher, openReviewLauncher, reviewTabs } from ". import { mockOpenCodeServer } from "../utils/mock-server" import { fileDiff, fileNode, openSession } from "../utils/workspace" import { expectSessionTitle } from "../utils/waits" +import { readFile } from "node:fs/promises" test.use({ viewport: { width: 1440, height: 900 } }) @@ -679,6 +680,276 @@ test("rereads a file each time an artifact link opens it", async ({ page }) => { await expect(missingTab).toHaveCount(0) }) +test("artifact actions copy and download content, switch source, and follow the selected file's capabilities", async ({ + page, + context, +}) => { + await context.grantPermissions(["clipboard-read", "clipboard-write"]) + const source = '' + const table = 'name,role\n"Jensen, Oliver",Researcher\nIsabella,Support' + + const workspace = await openSession(page, { + name: "ArtifactActions", + fileList: () => [], + fileContent: (path) => { + if (path === "vector.svg") return { content: source } + + if (path === "data.csv") return { content: table } + + if (path === "notes.md") return { content: "# Notes\n\nA document with a visible top edge." } + + return { type: "binary", content: "AAEC", encoding: "base64" } + }, + pageMessages: () => ({ + items: [ + { + id: "msg_artifact_actions", + type: "assistant", + agent: "build", + model: { id: "test", providerID: "opencode" }, + content: [ + { type: "text", text: "[Vector](vector.svg) [Table](data.csv) [Notes](notes.md) [Binary](sample.bin)" }, + ], + time: { created: 1, completed: 2 }, + }, + ], + }), + }) + + await page.getByRole("link", { name: "Vector", exact: true }).click() + const panel = page.locator("#review-panel") + const toolbar = panel.locator('[data-slot="artifact-toolbar"]:visible') + const actions = toolbar.getByRole("button", { name: "File actions", exact: true }) + const image = panel.getByRole("img", { name: "vector.svg", exact: true }) + await expect(image).toHaveJSProperty("naturalWidth", 120) + await expect(toolbar.getByText("vector.svg", { exact: true })).toBeVisible() + await panel.getByRole("button", { name: "Toggle file tree", exact: true }).click() + + // The source action stays visible at rest; only metadata needs hover or keyboard focus. + await page.mouse.move(0, 0) + const sourceAction = toolbar.getByRole("button", { name: "View source", exact: true }) + await expect(sourceAction).toHaveCSS("opacity", "1") + await expect(toolbar.locator('[data-slot="artifact-metadata"]')).toHaveCSS("opacity", "0") + await actions.focus() + await expect(toolbar.locator('[data-slot="artifact-metadata"]')).toHaveCSS("opacity", "1") + await expect(toolbar.getByText("120 × 80", { exact: true })).toBeVisible() + const copy = toolbar.getByRole("button", { name: "Copy content", exact: true }) + await copy.click() + await expect(page.getByText("Copied", { exact: true })).toBeVisible() + await expect.poll(() => page.evaluate(() => navigator.clipboard.readText())).toBe(source) + await page.getByRole("button", { name: "Dismiss", exact: true }).click() + + await sourceAction.click() + await expect(image).toHaveCount(0) + await expect(panel.locator("diffs-container")).toContainText(source) + await actions.click() + await expect(page.getByRole("menuitem", { name: "View preview", exact: true })).toBeVisible() + await expect(page.getByRole("menuitem", { name: "Open in", exact: true })).toHaveCount(0) + await page.getByRole("menuitem", { name: "View preview", exact: true }).click() + await expect(image).toHaveJSProperty("naturalWidth", 120) + + await page.getByRole("link", { name: "Table", exact: true }).click() + await expect(panel.getByRole("columnheader", { name: /^name(?:\s|$)/ })).toHaveCSS( + "background-color", + "rgb(242, 242, 242)", + ) + const nameCell = panel.getByRole("cell", { name: /^Jensen, Oliver(?:\s|$)/ }) + await expect(nameCell).toBeVisible() + await expect(toolbar.getByText("data.csv", { exact: true })).toBeVisible() + await nameCell.hover() + await nameCell.getByRole("button", { name: "Copy cell", exact: true }).click() + await expect.poll(() => page.evaluate(() => navigator.clipboard.readText())).toBe("Jensen, Oliver") + await toolbar.hover() + await expect(nameCell.getByRole("button", { name: "Copy cell", exact: true })).toHaveCSS("opacity", "0") + await page.keyboard.press("Tab") + + const nextCopy = panel + .getByRole("cell", { name: /^Researcher(?:\s|$)/ }) + .getByRole("button", { name: "Copy cell", exact: true }) + + await expect(nextCopy).toBeFocused() + await expect(nextCopy).toHaveCSS("opacity", "1") + + const copyHeader = panel + .getByRole("columnheader", { name: /^role(?:\s|$)/ }) + .getByRole("button", { name: "Copy cell", exact: true }) + + await copyHeader.focus() + await copyHeader.press("Enter") + await expect.poll(() => page.evaluate(() => navigator.clipboard.readText())).toBe("role") + await actions.click() + const downloaded = page.waitForEvent("download") + await page.getByRole("menuitem", { name: "Download", exact: true }).click() + const download = await downloaded + expect(download.suggestedFilename()).toBe("data.csv") + expect(await readFile((await download.path())!, "utf8")).toBe(table) + + await page.getByRole("link", { name: "Notes", exact: true }).click() + await expect(panel.getByRole("heading", { name: "Notes", exact: true })).toBeVisible() + const paper = panel.locator('[data-slot="artifact-markdown-page"]') + await expect(paper).toHaveCSS("border-radius", "8px") + await expect(paper).toHaveAttribute("data-component", "document-surface") + expect(await paper.evaluate((element) => getComputedStyle(element, "::after").borderTopStyle)).toBe("solid") + const surface = (await paper.boundingBox())! + const bar = (await toolbar.boundingBox())! + expect(surface.y - bar.y - bar.height).toBe(1) + await expect(panel.getByRole("group", { name: "Preview controls", exact: true })).toHaveCount(0) + + await page.getByRole("link", { name: "Binary", exact: true }).click() + await expect(panel.getByText(/Binary file/)).toBeVisible() + await expect(toolbar.getByText("sample.bin", { exact: true })).toBeVisible() + await expect(copy).toHaveCount(0) + await expect(toolbar.getByRole("button", { name: "View source", exact: true })).toHaveCount(0) + await actions.click() + await expect(page.getByRole("menuitem", { name: "Download", exact: true })).toHaveCount(0) + await page.getByRole("menuitem", { name: "Copy path", exact: true }).click() + await expect.poll(() => page.evaluate(() => navigator.clipboard.readText())).toBe(`${workspace.directory}/sample.bin`) +}) + +test("Markdown and DOCX sheets stay aligned when switching at wide and narrow preview widths", async ({ page }) => { + // Minimal DOCX containing one paragraph, "Document spacing", and a letter-sized page. + const docx = + "UEsDBBQAAAAIAI51W13mdcR+0gAAAIsBAAATAAAAW0NvbnRlbnRfVHlwZXNdLnhtbH2QvVLDMAzHX8XnlasVGBh6SToAKzD0BXSOkvjw11luad++Sls6cIVR+n/8ZLebQ/BqT4Vdip1+NI3e9O32mImVKJE7Pdea1wBsZwrIJmWKooypBKwylgky2i+cCJ6a5hlsipViXdWlQ/ftK42481W9HWR9oRTyrNXLxbiwOo05e2exig77OPyirK4EI8mzh2eX+UEMGu4SFuVvwDX3Ic8ubiD1iaW+YxAXfKcywJDsLkjS/F9z5840js7SLb+05ZIsMbs4BW9uSkAXf+6H83f3J1BLAwQUAAAACACOdVtdXzOVUpUAAAAHAQAACwAAAF9yZWxzLy5yZWxzjc87DsIwDAbgq0Q+QJ0yMKCmXVi6Ii4QJW5T0TzkhNftycBAEQOjf//6LHfDw6/iRpyXGBS0jYSh70606lKD7JaURW2ErMCVkg6I2TjyOjcxUaibKbLXpY48Y9LmomfCnZR75E8DtqYYrQIebQvi/Ez0jx2naTF0jObqKZQfJ74aVdY8U1Fwj2zRvuOmsoB9h5sX+xdQSwMEFAAAAAgAjnVbXUye0X++AAAAMQEAABEAAAB3b3JkL2RvY3VtZW50LnhtbEVQ0Q6CMAz8FbIPsEjUGILw4quJiV8wxwQSti5dFfXr7TCEl9v1ru01q5q3G7OXpTigP6ntJldNXU1li+bprOdMbB/L6aR65lACRNNbp+MGg/XiPZCcZimpgwmpDYTGxjj4zo1Q5PkBnB68Sivv2H7SGxJQAq7PS0wM2shQBUlNSDPOvdEavs4Dobt9syldsy2KXa6E98L3R+Hwb7hoEpUxiL77t9DQ9byWd2RGt9ajfSwuzKFLHiw3w/of9Q9QSwECFAMUAAAACACOdVtd5nXEftIAAACLAQAAEwAAAAAAAAAAAAAAgAEAAAAAW0NvbnRlbnRfVHlwZXNdLnhtbFBLAQIUAxQAAAAIAI51W11fM5VSlQAAAAcBAAALAAAAAAAAAAAAAACAAQMBAABfcmVscy8ucmVsc1BLAQIUAxQAAAAIAI51W11MntF/vgAAADEBAAARAAAAAAAAAAAAAACAAcEBAAB3b3JkL2RvY3VtZW50LnhtbFBLBQYAAAAAAwADALkAAACuAgAAAAA=" + + await page.setViewportSize({ width: 1728, height: 900 }) + await openSession(page, { + name: "DocumentAlignment", + fileList: () => [], + fileContent: (path) => + path === "notes.md" + ? { type: "text", content: "# Document spacing\n\nA Markdown sheet beside an Office document." } + : { + type: "binary", + content: docx, + encoding: "base64", + mimeType: "application/vnd.openxmlformats-officedocument.wordprocessingml.document", + }, + pageMessages: () => ({ + items: [ + { + id: "msg_document_alignment", + type: "assistant", + agent: "build", + model: { id: "test", providerID: "opencode" }, + content: [{ type: "text", text: "[Markdown](notes.md) [Word](sample.docx) [Second Word](other.docx)" }], + time: { created: 1, completed: 2 }, + }, + ], + }), + seed: { storage: { "opencode.global.dat:review-panel-v2": { sidebarOpened: false } } }, + }) + + const panel = page.locator("#review-panel") + const toolbar = panel.locator('[data-slot="artifact-toolbar"]:visible') + const markdown = panel.locator('[data-slot="artifact-markdown-page"]') + const word = panel.getByRole("group", { name: "Page 1", exact: true }) + + const edges = (sheet: Locator) => + sheet.evaluate((element) => { + const rect = element.getBoundingClientRect() + const scrollport = element.closest("[data-document-surface-scrollport]")! + + return { left: rect.left, right: rect.right, inset: rect.left - scrollport.getBoundingClientRect().left } + }) + + await page.getByRole("link", { name: "Markdown", exact: true }).click() + await page.getByRole("link", { name: "Word", exact: true }).click() + await expect(toolbar.getByText("sample.docx", { exact: true })).toBeVisible() + // The real Office engine may need a cold WASM initialization before its text layer is ready. + await expect(word.getByText("Document spacing", { exact: true })).toBeVisible({ timeout: 30_000 }) + await word.evaluate((element) => { + element.dataset.e2eProbe = "warm" + }) + const canvas = await word.locator("canvas").elementHandle() + expect(canvas).not.toBeNull() + await expect.poll(() => canvas!.evaluate((element) => Number(element.getAttribute("width")))).toBeGreaterThan(0) + await page.getByRole("link", { name: "Second Word", exact: true }).click() + await expect(toolbar.getByText("other.docx", { exact: true })).toBeVisible() + await expect(word.getByText("Document spacing", { exact: true })).toBeVisible({ timeout: 30_000 }) + await word.evaluate((element) => { + element.dataset.e2eProbe = "other-warm" + }) + + for (const size of [ + { width: 1728, gutter: 20 }, + { width: 1000, gutter: 12 }, + ]) { + await page.setViewportSize({ width: size.width, height: 900 }) + await panel.getByRole("tab", { name: "notes.md", exact: true }).click() + await expect(markdown.getByRole("heading", { name: "Document spacing", exact: true })).toBeVisible() + await toolbar.hover() + await expect.poll(async () => (await edges(markdown)).inset).toBeCloseTo(size.gutter, 1) + const reference = await edges(markdown) + const header = await toolbar.boundingBox() + + await panel.getByRole("tab", { name: "sample.docx", exact: true }).click() + await expect(word).toHaveAttribute("data-e2e-probe", "warm") + await expect(word.getByText("Document spacing", { exact: true })).toBeVisible() + await expect + .poll(() => edges(word)) + .toEqual({ + left: expect.closeTo(reference.left, 1), + right: expect.closeTo(reference.right, 1), + inset: expect.closeTo(size.gutter, 1), + }) + await expect.poll(() => toolbar.boundingBox()).toEqual(header) + + await panel.getByRole("tab", { name: "notes.md", exact: true }).click() + await expect(markdown.getByRole("heading", { name: "Document spacing", exact: true })).toBeVisible() + await expect.poll(() => edges(markdown)).toEqual(reference) + await expect.poll(() => toolbar.boundingBox()).toEqual(header) + expect(await canvas!.evaluate((element) => element.isConnected && Number(element.getAttribute("width")) > 0)).toBe(true) + await panel.getByRole("tab", { name: "other.docx", exact: true }).click() + await expect(word).toHaveAttribute("data-e2e-probe", "other-warm") + await panel.getByRole("tab", { name: "notes.md", exact: true }).click() + } + + await panel + .getByRole("tab", { name: "sample.docx", exact: true }) + .locator("..") + .getByRole("button", { name: "Close tab", exact: true }) + .click() + await expect.poll(() => canvas!.evaluate((element) => element.isConnected)).toBe(false) +}) + +test("diagram preview controls zoom the rendered diagram and fit it back into its pane", async ({ page }) => { + await openSession(page, { + name: "DiagramZoom", + fileList: () => [], + fileContent: () => ({ content: "flowchart LR\n Start[Start] --> Review[Review] --> Finish[Finish]" }), + pageMessages: () => ({ + items: [ + { + id: "msg_diagram_zoom", + type: "assistant", + agent: "build", + model: { id: "test", providerID: "opencode" }, + content: [{ type: "text", text: "[Diagram](flow.mmd)" }], + time: { created: 1, completed: 2 }, + }, + ], + }), + }) + await page.getByRole("link", { name: "Diagram", exact: true }).click() + const panel = page.locator("#review-panel") + const diagram = panel.locator('[data-component="markdown-mermaid"] > svg') + const controls = panel.getByRole("group", { name: "Preview controls", exact: true }) + const fit = controls.getByRole("button", { name: "Fit", exact: true }) + await expect(panel.getByText("Finish", { exact: true })).toBeVisible() + await diagram.hover() + const initial = (await diagram.boundingBox())! + + await expect(fit).toBeEnabled() + await controls.getByRole("button", { name: "Zoom in", exact: true }).click() + await expect.poll(async () => (await diagram.boundingBox())!.width).toBeCloseTo(initial.width * 1.25, 1) + await controls.getByRole("button", { name: "Zoom out", exact: true }).click() + await expect.poll(async () => (await diagram.boundingBox())!.width).toBeCloseTo(initial.width, 1) + await controls.getByRole("button", { name: "Zoom out", exact: true }).click() + await expect.poll(async () => (await diagram.boundingBox())!.width).toBeCloseTo(initial.width / 1.25, 1) + await fit.click() + await expect.poll(() => diagram.boundingBox()).toEqual(initial) +}) + /** What the image case's frame probe records on the window. */ type ImageProbe = { problems: string[]; frames: number; running: boolean } @@ -698,12 +969,20 @@ test("image gestures anchor zoom, pan, and reset independently of the pane", asy await openSession(page, { name: "ImageGestures", fileList: () => [], - fileContent: (path) => ({ - content: - path === "second.svg" - ? '' - : '', - }), + fileContent: (path) => { + if (path === "small.svg") + return { + content: + '', + } + + return { + content: + path === "second.svg" + ? '' + : '', + } + }, pageMessages: () => ({ items: [ { @@ -711,7 +990,7 @@ test("image gestures anchor zoom, pan, and reset independently of the pane", asy type: "assistant", agent: "build", model: { id: "test", providerID: "opencode" }, - content: [{ type: "text", text: "[First](first.svg) [Second](second.svg)" }], + content: [{ type: "text", text: "[First](first.svg) [Second](second.svg) [Small](small.svg)" }], time: { created: 1, completed: 2 }, }, ], @@ -723,11 +1002,15 @@ test("image gestures anchor zoom, pan, and reset independently of the pane", asy const stage = panel.locator('[data-slot="artifact-stage"]') const fit = panel.getByRole("button", { name: "Fit", exact: true }) await expect(image).toBeVisible() - await expect(fit).toBeDisabled() + await expect(fit).toBeEnabled() // Wait for the side pane's opening motion before choosing a gesture anchor. await image.hover() const initial = (await image.boundingBox())! const pane = (await panel.boundingBox())! + await panel.getByRole("button", { name: "Zoom in", exact: true }).click() + await expect.poll(async () => (await image.boundingBox())!.width).toBeCloseTo(initial.width * 1.25, 1) + await panel.getByRole("button", { name: "Zoom out", exact: true }).click() + await expect.poll(() => image.boundingBox()).toEqual(initial) const anchor = { x: Math.round(initial.x + initial.width * 0.55), y: Math.round(initial.y + initial.height * 0.55) } await page.mouse.move(anchor.x, anchor.y) // A continuous pinch catches anchor drift while the image still fits one axis. @@ -739,7 +1022,7 @@ test("image gestures anchor zoom, pan, and reset independently of the pane", asy gestureSourceType: "mouse", }) await cdp.detach() - await expect(fit).toBeEnabled() + await expect(stage).toHaveAttribute("data-zoom", "actual") const zoomed = (await image.boundingBox())! expect(zoomed.width).toBeCloseTo(initial.width * 2, 1) expect((anchor.x - zoomed.x) / zoomed.width).toBeCloseTo((anchor.x - initial.x) / initial.width, 4) @@ -753,7 +1036,7 @@ test("image gestures anchor zoom, pan, and reset independently of the pane", asy await page.mouse.down() await page.mouse.move(anchor.x + 60, anchor.y + 40, { steps: 5 }) await page.mouse.up() - await expect(fit).toBeEnabled() + await expect(stage).toHaveAttribute("data-zoom", "actual") expect((await image.boundingBox())!.x).toBeCloseTo(scrolled.x + 60, 1) expect((await image.boundingBox())!.y).toBeCloseTo(scrolled.y + 40, 1) // Touch uses the same captured-pointer path and must not generate a click-to-fit. @@ -765,13 +1048,13 @@ test("image gestures anchor zoom, pan, and reset independently of the pane", asy }) await touch.send("Input.dispatchTouchEvent", { type: "touchEnd", touchPoints: [] }) await touch.detach() - await expect(fit).toBeEnabled() + await expect(stage).toHaveAttribute("data-zoom", "actual") expect((await image.boundingBox())!.x).toBeCloseTo(scrolled.x + 30, 1) expect((await image.boundingBox())!.y).toBeCloseTo(scrolled.y + 20, 1) // Keyboard-accessible fit restores the exact original geometry. await fit.focus() await page.keyboard.press("Enter") - await expect(fit).toBeDisabled() + await expect(stage).toHaveAttribute("data-zoom", "fit") expect(await image.boundingBox()).toEqual(initial) expect( await stage.evaluate((element) => @@ -779,17 +1062,17 @@ test("image gestures anchor zoom, pan, and reset independently of the pane", asy ), ).toBe(true) await image.click() - await expect(fit).toBeEnabled() + await expect(stage).toHaveAttribute("data-zoom", "actual") await page.getByRole("link", { name: "Second", exact: true }).click() await expect(panel.getByRole("img", { name: "second.svg", exact: true })).toBeVisible() - await expect(fit).toBeDisabled() + await expect(stage).toHaveAttribute("data-zoom", "fit") await panel.getByRole("img", { name: "second.svg", exact: true }).hover() const second = (await panel.getByRole("img", { name: "second.svg", exact: true }).boundingBox())! expect(second.width).toBeGreaterThan(0) expect(second.height).toBeGreaterThan(0) await page.keyboard.down("Control") await page.mouse.wheel(0, -50) - await expect(fit).toBeEnabled() + await expect(stage).toHaveAttribute("data-zoom", "actual") await page.keyboard.up("Control") await fit.click() await page.setViewportSize({ width: 1200, height: 700 }) @@ -801,6 +1084,14 @@ test("image gestures anchor zoom, pan, and reset independently of the pane", asy return media.width <= frame.width - 47 && media.height <= frame.height - 47 }) .toBe(true) + await page.getByRole("link", { name: "Small", exact: true }).click() + const small = panel.getByRole("img", { name: "small.svg", exact: true }) + await expect(small).toHaveJSProperty("naturalWidth", 32) + await small.click() + await expect.poll(async () => (await small.boundingBox())!.width).toBeCloseTo(32, 1) + await expect(panel.getByRole("button", { name: "Zoom out", exact: true })).toBeDisabled() + await fit.click() + await expect.poll(async () => (await small.boundingBox())!.width).toBeGreaterThan(128) }) test("image files load into the review panel and keep it painted while loading", async ({ page }) => { diff --git a/packages/gui-plugins/src/file/artifact-toolbar.tsx b/packages/gui-plugins/src/file/artifact-toolbar.tsx new file mode 100644 index 00000000000..ee703db256a --- /dev/null +++ b/packages/gui-plugins/src/file/artifact-toolbar.tsx @@ -0,0 +1,161 @@ +import { For, Show } from "solid-js" +import { createStore } from "solid-js/store" +import { Icon } from "@opencode/ui/icon" +import { IconButton } from "@opencode/ui/icon-button" +import { Menu } from "@opencode/ui/menu" +import { Tooltip } from "@opencode/ui/tooltip" +import { showToast } from "@opencode/ui/toast" +import { artifactKind } from "@opencode/util/artifact" +import { getFilename } from "@opencode/util/path" +import { usePlugin, type MountedSession, type SessionScreen } from "@opencode/plugin/gui" +import { current, useShared } from "./context" +import { OpenInAppMenuItemsV2, useOpenInApp } from "./open-in-app" +import { resolveOpenInAppPath, workspaceFileUrl } from "./path" + +export function ArtifactToolbar(props: { + session: MountedSession + screen: SessionScreen + path: string + text?: string + mode: "preview" | "source" + onModeChange?: (mode: "preview" | "source") => void + meta: string[] + html: boolean +}) { + const ctx = usePlugin() + const shared = useShared() + const [store, setStore] = createStore({ open: false }) + const path = () => resolveOpenInAppPath(props.screen.file.root, props.path) + const kind = () => artifactKind(props.path) + + const apps = useOpenInApp({ + get session() { + return props.session + }, + path, + }) + + const browser = () => { + if (!props.html) return + const pane = current(shared.browser()) + + return pane?.canOpen(props.session, props.path) ? pane : undefined + } + + const modeLabel = () => ctx.t(props.mode === "preview" ? "view.viewSource" : "view.viewPreview") + const toggleMode = () => props.onModeChange?.(props.mode === "preview" ? "source" : "preview") + + const failed = () => { + if (ctx.signal.aborted) return + showToast({ variant: "error", title: ctx.t("common.requestFailed") }) + } + + const copy = (text: string) => { + void ctx.system + .copy(text) + .then(() => { + if (ctx.signal.aborted) return + showToast({ variant: "success", title: ctx.t("common.copied") }) + }) + .catch(failed) + } + + return ( +
+
+ {getFilename(props.path)} +
+
+
+ + {(item, index) => ( + <> + 0}> + · + + + {item} + + + )} + +
+
+ + + } + /> + + + + + copy(props.text ?? "")} + icon={} + /> + + + setStore("open", open)}> + } + /> + + + + { + void ctx.system.save({ name: getFilename(props.path), content: props.text ?? "" }).catch(failed) + }} + > + {ctx.t("view.download")} + + + + {modeLabel()} + + + {(pane) => ( + pane().open(props.session, workspaceFileUrl(props.screen.file.root, props.path))} + > + {ctx.t("view.openInBrowser")} + + )} + + + apps.openPath("finder", path(), true)} disabled={apps.opening()}> + {ctx.t("view.reveal", { app: apps.options()[0].label })} + + + copy(path())}>{ctx.t("open.copyPath")} + + + {ctx.t("open.in")} + + + setStore("open", false)} /> + + + + + + + +
+
+
+ ) +} diff --git a/packages/gui-plugins/src/file/artifact-view.css b/packages/gui-plugins/src/file/artifact-view.css index 7e6df8c7303..47d3b99ad84 100644 --- a/packages/gui-plugins/src/file/artifact-view.css +++ b/packages/gui-plugins/src/file/artifact-view.css @@ -1,36 +1,94 @@ -/* The control defaults to a fixed 232px with equal segments; here it hugs its two labels. */ -[data-slot="artifact-toolbar"] [data-slot="segmented-control-v2"] { - width: auto; +@import "@opencode/ui/document-surface.css"; + +[data-slot="artifact-view"] { + --opencode-diffs-bg: var(--v2-background-bg-layer-01); + container-type: inline-size; + background-color: var(--v2-background-bg-layer-01); } -[data-slot="artifact-toolbar"] [data-slot="segmented-control-v2-item"] { - flex: 0 0 auto; - padding: 0 14px; +[data-slot="artifact-toolbar"] { + display: flex; + flex-shrink: 0; + align-items: center; + gap: 12px; + height: 44px; + padding-inline: 20px 12px; + background-color: var(--v2-background-bg-layer-01); } -/* Shrink-wrapped segments round the label box down a fraction; the ellipsis overflow then clips glyph edges. */ -[data-slot="artifact-toolbar"] [data-slot="segmented-control-v2-item-label"] { - overflow: visible; - max-width: none; +[data-slot="artifact-filename"] { + flex: 1; + min-width: 0; + overflow: hidden; + text-overflow: ellipsis; + white-space: nowrap; + color: var(--v2-text-text-base); + font-size: 13px; + font-weight: var(--font-weight-medium); + line-height: var(--line-height-compact); +} + +[data-slot="artifact-toolbar-trailing"], +[data-slot="artifact-toolbar-actions"] { + display: flex; + align-items: center; + gap: 8px; +} + +[data-slot="artifact-toolbar-trailing"] { + min-width: 0; + max-width: 65%; + gap: 12px; +} + +[data-slot="artifact-toolbar-actions"] { + flex-shrink: 0; +} + +[data-slot="artifact-metadata"] { + display: flex; + align-items: center; + gap: 6px; + min-width: 0; + color: var(--v2-text-text-faint); + font-size: 13px; + line-height: var(--line-height-compact); + font-variant-numeric: tabular-nums; + white-space: nowrap; +} + +/* Reserve the metadata slot so revealing details never shifts the filename or actions. */ +@media (hover: hover) and (pointer: fine) { + [data-slot="artifact-metadata"] { + opacity: 0; + } + + [data-slot="artifact-toolbar"]:hover [data-slot="artifact-metadata"], + [data-slot="artifact-toolbar"]:focus-within [data-slot="artifact-metadata"], + [data-slot="artifact-toolbar"][data-menu-open] [data-slot="artifact-metadata"] { + opacity: 1; + } +} + +.artifact-actions-menu { + min-width: 160px; +} + +@container (max-width: 600px) { + [data-slot="artifact-metadata"] { + display: none; + } +} + +@media (pointer: coarse) { + [data-slot="artifact-toolbar-actions"] [data-component="icon-button-v2"] { + width: 44px; + height: 44px; + } } [data-slot="artifact-stage"] { - --artifact-check: color-mix(in oklch, var(--v2-text-text-base) 5%, transparent); - background-color: var(--v2-background-bg-deep); -} - -[data-slot="artifact-stage"][data-checker] { - background-image: - linear-gradient(45deg, var(--artifact-check) 25%, transparent 25%), - linear-gradient(-45deg, var(--artifact-check) 25%, transparent 25%), - linear-gradient(45deg, transparent 75%, var(--artifact-check) 75%), - linear-gradient(-45deg, transparent 75%, var(--artifact-check) 75%); - background-size: 16px 16px; - background-position: - 0 0, - 0 8px, - 8px -8px, - -8px 0; + background-color: var(--v2-background-bg-layer-01); } [data-slot="artifact-media"] { @@ -41,6 +99,11 @@ 0 12px 32px -12px color-mix(in oklch, var(--v2-text-text-base) 25%, transparent); } +img[data-slot="artifact-media"] { + border-radius: 0; + box-shadow: none; +} + [data-slot="artifact-media"]::-webkit-media-controls-fullscreen-button { visibility: hidden; pointer-events: none; @@ -73,36 +136,130 @@ border-collapse: separate; border-spacing: 0; font-variant-numeric: tabular-nums; + background: var(--v2-background-bg-base); + color: var(--v2-text-text-base); } [data-slot="artifact-table"] th, [data-slot="artifact-table"] td { + position: relative; + height: 28px; padding: 5px 12px; - border-bottom: 1px solid var(--v2-border-border-muted); - border-inline-end: 1px solid var(--v2-border-border-muted); + padding-inline-end: 36px; + border-bottom: 0.5px solid var(--v2-border-border-muted); + border-inline-end: 0.5px solid var(--v2-border-border-muted); white-space: pre; max-width: 40ch; - overflow: hidden; - text-overflow: ellipsis; text-align: start; line-height: var(--line-height-compact); } +[data-slot="artifact-table-cell-text"] { + display: block; + overflow: hidden; + text-overflow: ellipsis; + user-select: text; +} + +[data-slot="artifact-table-copy"] { + position: absolute; + inset-inline-end: 6px; + top: 50%; + transform: translateY(-50%); + opacity: 0; + pointer-events: none; +} + +[data-slot="artifact-table-copy"]:focus-visible { + opacity: 1; + pointer-events: auto; +} + +@media (hover: hover) { + [data-slot="artifact-table"] :is(th, td):hover [data-slot="artifact-table-copy"] { + opacity: 1; + pointer-events: auto; + } +} + +@media (hover: none), (pointer: coarse) { + [data-slot="artifact-table-copy"] { + opacity: 1; + pointer-events: auto; + } +} + +@media (pointer: coarse) { + [data-slot="artifact-table"] :is(th, td) { + height: 48px; + padding-inline-end: 60px; + } + + [data-slot="artifact-table-copy"] { + width: 44px; + height: 44px; + } +} + [data-slot="artifact-table"] th { position: sticky; top: 0; z-index: 1; - background: var(--v2-background-bg-layer-01); + background: var(--v2-background-bg-layer-02); + border-top: 0.5px solid var(--v2-border-border-base); + border-bottom-color: var(--v2-border-border-base); + border-inline-end-color: var(--v2-border-border-base); font-weight: var(--font-weight-medium); color: var(--v2-text-text-muted); } -[data-slot="artifact-table"] tbody tr:hover td { - background: color-mix(in oklch, var(--v2-text-text-base) 3%, transparent); +[data-slot="artifact-table"] th:last-child { + border-inline-end: 0; } -[data-slot="artifact-table"] td[data-index] { - color: var(--v2-text-text-faint); - text-align: end; - user-select: none; +@media (hover: hover) { + [data-slot="artifact-table"] tbody tr:hover td { + background: var(--v2-overlay-simple-overlay-hover); + } +} + +[data-slot="artifact-table"] th:first-child, +[data-slot="artifact-table"] td:first-child { + padding-inline-start: 20px; +} + +[data-slot="artifact-document-stage"][data-kind="markdown"], +[data-slot="artifact-document-stage"][data-kind="font"] { + padding-block-end: 20px; +} + +[data-slot="artifact-markdown-page"] { + min-height: 100%; + padding: 64px clamp(24px, 12.5%, 134px); +} + +[data-slot="artifact-markdown-content"] { + width: 100%; + max-width: 768px; + margin-inline: auto; +} + +[data-slot="artifact-diagram"] { + min-width: 0; + padding: 24px 32px; +} + +@container (max-width: 600px) { + [data-slot="artifact-document-stage"][data-kind="markdown"], + [data-slot="artifact-document-stage"][data-kind="font"] { + padding-block-end: 12px; + } + + [data-slot="artifact-markdown-page"] { + padding: 32px 24px; + } + + [data-slot="artifact-diagram"] { + padding: 20px 12px; + } } diff --git a/packages/gui-plugins/src/file/artifact-view.tsx b/packages/gui-plugins/src/file/artifact-view.tsx index adc6609d4d8..80da8916f0d 100644 --- a/packages/gui-plugins/src/file/artifact-view.tsx +++ b/packages/gui-plugins/src/file/artifact-view.tsx @@ -13,21 +13,22 @@ import { import { createStore } from "solid-js/store" import { Dynamic } from "solid-js/web" import { createResizeObserver } from "@solid-primitives/resize-observer" -import { Button } from "@opencode/ui/button" +import { PreviewControls } from "@opencode/ui/preview-controls" import { useDialog } from "@opencode/ui/context/dialog" import { FileIcon } from "@opencode/ui/file-icon" +import { Icon } from "@opencode/ui/icon" +import { IconButton } from "@opencode/ui/icon-button" import { ImagePreview } from "@opencode/ui/image-preview" -import { SegmentedControl, SegmentedControlItem } from "@opencode/ui/segmented-control" import { Loader } from "@opencode/ui/loader" +import { showToast } from "@opencode/ui/toast" import { Markdown } from "@opencode/session-ui/markdown" import { MarkdownProvider, useMarkdown } from "@opencode/session-ui/context/markdown" import { artifactKind, type ArtifactKind } from "@opencode/util/artifact" import { getDirectory, getFilename } from "@opencode/util/path" -import { createKeyed, usePlugin, type FileContent, type MountedSession } from "@opencode/plugin/gui" +import { createKeyed, usePlugin, type FileContent, type MountedSession, type SessionScreen } from "@opencode/plugin/gui" import { blobUrlFromContent, bytesFromContent, contentBytes, parseDelimited, resolveArtifactPath } from "./artifact" -import { current, useShared } from "./context" import { FileViewer } from "@opencode/plugin/gui/file" -import { workspaceFileUrl } from "./path" +import { ArtifactToolbar } from "./artifact-toolbar" type ArtifactMode = "preview" | "source" @@ -67,6 +68,7 @@ const previewableKinds: readonly ArtifactKind[] = ["svg", "html", "markdown", "m */ export default function ArtifactView(props: { session: MountedSession + screen: SessionScreen path: string content: FileContent cacheKey?: string @@ -112,10 +114,10 @@ export default function ArtifactView(props: { const info: ArtifactInfo = parsed ? { rows: parsed.total, columns: parsed.columns } : state().info return [ - info.width && info.height ? `${info.width} × ${info.height}` : undefined, info.duration ? formatDuration(info.duration) : undefined, - info.rows !== undefined ? ctx.plural("view.table.rows", Math.max(0, info.rows - 1)) : undefined, + info.width && info.height ? `${info.width} × ${info.height}` : undefined, info.columns !== undefined ? ctx.plural("view.table.columns", info.columns) : undefined, + info.rows !== undefined ? ctx.plural("view.table.rows", Math.max(0, info.rows - 1)) : undefined, ...(info.details ?? []), formatBytes(locale.locale(), contentBytes(props.content)), ].filter((item): item is string => !!item) @@ -136,10 +138,18 @@ export default function ArtifactView(props: { }) const rendered = () => ( -
- } + } + > +
- -
+
+ ) return ( - <> +
change({ mode }) : undefined} meta={meta()} - actions={ - - - - } + html={kind() === "html"} /> }> @@ -197,7 +211,7 @@ export default function ArtifactView(props: { - +
) } @@ -222,80 +236,6 @@ function formatDuration(seconds: number) { return `${minutes}:${String(total % 60).padStart(2, "0")}` } -function ArtifactToolbar(props: { - mode?: ArtifactMode - onModeChange?: (mode: ArtifactMode) => void - meta: string[] - actions?: JSX.Element -}) { - const ctx = usePlugin() - - return ( -
- - { - if (value === "preview" || value === "source") props.onModeChange?.(value) - }} - > - {ctx.t("view.preview")} - {ctx.t("view.source")} - - -
-
- - {(item, index) => ( - <> - 0}> - - · - - - {item} - - )} - -
- {props.actions} -
-
- ) -} - -/** Shows only while the browser pane is active and can load the file. */ -function OpenInBrowserButton(props: { session: MountedSession; path: string }) { - const ctx = usePlugin() - const shared = useShared() - - const pane = () => { - const browser = current(shared.browser()) - - return browser?.canOpen(props.session, props.path) ? browser : undefined - } - - return ( - - {(browser) => ( - - )} - - ) -} - function createMediaUrl(content: () => FileContent) { return createMemo(() => { const streamed = content().url @@ -335,8 +275,6 @@ function ArtifactImage(props: MediaProps) { } function ImageStage(props: MediaProps & { src: string }) { - const ctx = usePlugin() - const [view, setView] = createStore({ width: 0, height: 0, @@ -350,15 +288,18 @@ function ImageStage(props: MediaProps & { src: string }) { const fit = () => Math.min( - 1, + artifactKind(props.path) === "svg" ? Infinity : 1, Math.max(1, view.width - 48) / (view.imageWidth || 1), Math.max(1, view.height - 48) / (view.imageHeight || 1), ) + const minZoom = () => Math.min(0.25, 1 / fit()) + const maxZoom = () => Math.max(8, 1 / fit()) + const bound = (offset: number, image: number, zoom: number) => { // Keep the fitted footprint covered, including its letterboxing. Clamping to // the stage edges instead would move the anchor during small pinch increments. - const limit = (image * fit() * (zoom - 1)) / 2 + const limit = Math.max(0, (image * fit() * (zoom - 1)) / 2) return Math.max(-limit, Math.min(limit, offset)) } @@ -375,7 +316,7 @@ function ImageStage(props: MediaProps & { src: string }) { let dragged = false const cursor = () => { - if (view.zoom === 1) return undefined + if (view.zoom <= 1) return undefined return view.dragging ? "grabbing" : "grab" } @@ -391,7 +332,7 @@ function ImageStage(props: MediaProps & { src: string }) { if (!stage) return const rect = stage.getBoundingClientRect() - const next = Math.max(1, Math.min(Math.max(8, 1 / fit()), zoom)) + const next = Math.max(minZoom(), Math.min(maxZoom(), zoom)) const ratio = next / view.zoom const anchor = { x: clientX - rect.left - rect.width / 2, y: clientY - rect.top - rect.height / 2 } setView({ @@ -401,6 +342,13 @@ function ImageStage(props: MediaProps & { src: string }) { }) } + const zoomBy = (factor: number) => { + if (!stage) return + const rect = stage.getBoundingClientRect() + + zoomAt(view.zoom * factor, rect.left + rect.width / 2, rect.top + rect.height / 2) + } + createResizeObserver( () => stage, () => { @@ -415,12 +363,11 @@ function ImageStage(props: MediaProps & { src: string }) {
{ - if (!view.imageWidth || (!event.ctrlKey && view.zoom === 1)) return + if (!view.imageWidth || (!event.ctrlKey && view.zoom <= 1)) return // Chromium delivers trackpad pinch as Ctrl-wheel. Consume it here before // Desktop's window-level zoom handler; ordinary fitted scrolling stays native. @@ -458,7 +405,7 @@ function ImageStage(props: MediaProps & { src: string }) { dragged = false - if (view.zoom === 1) return + if (view.zoom <= 1) return drag = { id: event.pointerId, clientX: event.clientX, clientY: event.clientY, x: x(), y: y() } event.currentTarget.setPointerCapture(event.pointerId) @@ -499,7 +446,7 @@ function ImageStage(props: MediaProps & { src: string }) { return } - if (view.zoom > 1) return reset() + if (view.zoom !== 1) return reset() zoomAt(1 / fit(), event.clientX, event.clientY) }} @@ -507,11 +454,14 @@ function ImageStage(props: MediaProps & { src: string }) { -
- -
+ = maxZoom()} + zoomOutDisabled={view.zoom <= minZoom()} + onZoomIn={() => zoomBy(1.25)} + onZoomOut={() => zoomBy(1 / 1.25)} + onFit={reset} + />
) } @@ -638,14 +588,7 @@ function ArtifactVideo(props: MediaProps) { }} > - + @@ -659,9 +602,9 @@ function ArtifactAudio(props: MediaProps) { return (
-
+
- +
{getFilename(props.path)}