Skip to content

armgit / alook

Public Imported from GitHub
0

Multi-Agent Collaboration for Team and Friends

fix(web): simplify HTML previews and align block action sizes (#1109)

Gener319320df31c6
diff --git a/src/web/src/app/globals.css b/src/web/src/app/globals.css
index 01abb74a8..8fd8f52f9 100644
--- a/src/web/src/app/globals.css
+++ b/src/web/src/app/globals.css
@@ -2485,11 +2485,6 @@ html.dark .blog-content [data-rehype-pretty-code-figure] span {
opacity: 1;
pointer-events: auto;
}
-
- [data-html-preview-actions] button {
- width: 2.75rem !important;
- height: 2.75rem !important;
- }
}
/* ── Streamdown block actions: dropdown popups ── */
diff --git a/src/web/src/components/community/messages/html-attachment-preview.dom.test.tsx b/src/web/src/components/community/messages/html-attachment-preview.dom.test.tsx
index 8406898c9..9a8bcfffd 100644
--- a/src/web/src/components/community/messages/html-attachment-preview.dom.test.tsx
+++ b/src/web/src/components/community/messages/html-attachment-preview.dom.test.tsx
@@ -37,7 +37,10 @@ describe("HTML attachment frame", () => {
const actions = view.getByRole("group", { name: "HTML preview actions" })
expect(view.queryByText(file.name)).toBeNull()
expect(actions).toContainElement(view.getByTestId(tid.htmlPreviewDownload("a1")))
- expect(actions).toContainElement(view.getByTestId(tid.htmlPreviewExpand("a1")))
+ expect(actions.querySelectorAll("button")).toHaveLength(1)
+ expect(view.queryByRole("button", { name: /Expand HTML preview|Close fullscreen preview/ })).toBeNull()
+ expect(view.queryByRole("dialog")).toBeNull()
+ expect(view.getByTestId(tid.htmlPreview("a1"))).not.toHaveAttribute("aria-modal")
expect(view.getByTestId(tid.htmlPreview("a1"))).toHaveAccessibleName(file.name)
})
it("keeps one opaque-origin frame and clamps valid current-frame measurements", () => {
@@ -72,65 +75,42 @@ describe("HTML attachment frame", () => {
expect(post).toHaveBeenLastCalledWith(expect.objectContaining({ dark: true }), "*")
document.documentElement.style.removeProperty("--background")
})
- it("expands and returns the same frame, with Escape and focus recovery", () => {
- const view = setup(), frame = view.getByTestId(tid.htmlPreviewFrame("a1"))
- const dialog = view.getByTestId(tid.htmlPreview("a1")) as HTMLDialogElement
- Object.assign(dialog, {
- getBoundingClientRect() { return { height: 420 } },
- close() { dialog.open = false },
- show() { dialog.open = true },
- showModal() { dialog.open = true },
- })
- fireEvent.click(view.getByTestId(tid.htmlPreviewExpand("a1")))
- expect(view.getByRole("dialog")).toHaveAttribute("aria-modal", "true")
- expect(dialog.parentElement!.style.height).toBe("420px")
- expect(view.getByTestId(tid.htmlPreviewFrame("a1"))).toBe(frame)
- fireEvent(view.getByRole("dialog"), new Event("cancel", { cancelable: true }))
- expect(view.queryByRole("dialog")).toBeNull()
- expect(dialog.parentElement!.style.height).toBe("")
+ it("keeps an icon-only loading status until the current lazy frame reports ready", () => {
+ let intersect: IntersectionObserverCallback | undefined
+ vi.stubGlobal("IntersectionObserver", class { constructor(callback: IntersectionObserverCallback) { intersect = callback } observe() {} disconnect() {} })
+ const view = setup()
+ const preview = view.getByTestId(tid.htmlPreview("a1"))
+ const loading = view.getByRole("status", { name: "Loading preview" })
+ expect(loading.textContent).toBe("")
+ expect(loading.querySelector("svg")).toHaveAttribute("aria-hidden", "true")
+ expect(preview.style.height).toBe("320px")
+ expect(view.queryByTestId(tid.htmlPreviewFrame("a1"))).toBeNull()
+ act(() => intersect!([{ isIntersecting: true } as IntersectionObserverEntry], {} as IntersectionObserver))
+ const frame = view.getByTestId(tid.htmlPreviewFrame("a1")) as HTMLIFrameElement
+ expect(preview.style.height).toBe("")
+ expect(frame.style.height).toBe("320px")
+ fireEvent.load(frame)
+ frameMessage(frame, { type: "alook-html-ready" }, { source: window })
+ expect(view.getByRole("status", { name: "Loading preview" })).toBe(loading)
+ frameMessage(frame, { type: "alook-html-ready" })
+ expect(view.queryByRole("status", { name: "Loading preview" })).toBeNull()
expect(view.getByTestId(tid.htmlPreviewFrame("a1"))).toBe(frame)
- expect(view.getByTestId(tid.htmlPreviewExpand("a1"))).toHaveFocus()
+ expect(preview).toHaveAttribute("data-html-preview-status", "ready")
})
- it("returns native Back from fullscreen to the same inline document before page navigation", () => {
+ it("leaves native Back to the normal page route with an inline preview", () => {
const originalUrl = window.location.href
const replacePath = vi.fn((path: string) => window.history.replaceState(null, "", path))
window.history.replaceState(null, "", "/c/channels/server/channel")
try {
const view = setup(<><BackListener replacePath={replacePath} /><textarea aria-label="Host draft" defaultValue="saved draft" /><HtmlAttachmentPreview attachment={file} /></>)
- const frame = view.getByTestId(tid.htmlPreviewFrame("a1")) as HTMLIFrameElement
- const frameDocument = frame.contentDocument!
- const html = frameDocument.createElement("html")
- const body = frameDocument.createElement("body")
- const input = frameDocument.createElement("input")
- input.id = "preview-state"
- input.value = "kept value"
- body.appendChild(input)
- html.appendChild(body)
- frameDocument.replaceChildren(html)
- const dialog = view.getByTestId(tid.htmlPreview("a1")) as HTMLDialogElement
- Object.assign(dialog, {
- close() { dialog.open = false },
- show() { dialog.open = true },
- showModal() { dialog.open = true },
- })
- fireEvent.click(view.getByTestId(tid.htmlPreviewExpand("a1")))
- const url = window.location.href
- const src = frame.src
+ const frame = view.getByTestId(tid.htmlPreviewFrame("a1"))
const event = new Event(NATIVE_MOBILE_BACK_EVENT, { cancelable: true })
act(() => { window.dispatchEvent(event) })
expect(event.defaultPrevented).toBe(true)
- expect(view.getByTestId(tid.htmlPreview("a1"))).not.toHaveAttribute("aria-modal", "true")
- expect(replacePath).not.toHaveBeenCalled()
- expect(window.location.href).toBe(url)
+ expect(replacePath).toHaveBeenCalledExactlyOnceWith("/c/me")
expect(view.getByTestId(tid.htmlPreviewFrame("a1"))).toBe(frame)
- expect(frame.src).toBe(src)
- expect(frame.contentDocument).toBe(frameDocument)
- expect(frameDocument.getElementById("preview-state")).toBe(input)
- expect(input.value).toBe("kept value")
+ expect(view.queryByRole("dialog")).toBeNull()
expect(view.getByRole("textbox", { name: "Host draft" })).toHaveValue("saved draft")
- expect(view.getByTestId(tid.htmlPreviewExpand("a1"))).toHaveFocus()
- act(() => { window.dispatchEvent(new Event(NATIVE_MOBILE_BACK_EVENT, { cancelable: true })) })
- expect(replacePath).toHaveBeenCalledExactlyOnceWith("/c/me")
} finally { window.history.replaceState(null, "", originalUrl) }
})
it("waits until near the viewport and cleans up on owner retirement", () => {
@@ -167,7 +147,7 @@ describe("HTML attachment frame", () => {
expect(view.getByRole("status")).toHaveTextContent("Preview unavailable")
expect(view.getAllByTestId(tid.htmlPreview("a1"))).toHaveLength(1)
expect(view.getByTestId(tid.htmlPreviewDownload("a1"))).toBeEnabled()
- expect(view.getByTestId(tid.htmlPreviewExpand("a1"))).toBeDisabled()
+ expect(view.queryByRole("status", { name: "Loading preview" })).toBeNull()
})
})
@@ -179,7 +159,7 @@ describe("HTML marker rendering", () => {
expect(view.container.textContent).toContain("after")
const body = view.container.querySelector(".message-markdown-blocks")!
expect([...body.children].map((node) => node.tagName)).toEqual(["P", "DIV", "P"])
- expect(view.container.querySelector("p dialog")).toBeNull()
+ expect(view.container.querySelector("p [data-html-preview]")).toBeNull()
})
it("does not execute typed HTML tags or let them duplicate a valid marker", () => {
const literal = '<htmlpreview data-attachment-id="a1"></htmlpreview>'
diff --git a/src/web/src/components/community/messages/html-attachment-preview.tsx b/src/web/src/components/community/messages/html-attachment-preview.tsx
index ba3ea032d..3f94b4424 100644
--- a/src/web/src/components/community/messages/html-attachment-preview.tsx
+++ b/src/web/src/components/community/messages/html-attachment-preview.tsx
@@ -3,7 +3,7 @@
import { useQuery } from "@tanstack/react-query"
import { useSelector } from "@tanstack/react-store"
import { useEffect, useMemo, useRef, useState } from "react"
-import { Download, Expand, LoaderCircle, X } from "lucide-react"
+import { Download, LoaderCircle } from "lucide-react"
import { useTheme } from "next-themes"
import { collectHtmlPreviewFonts, loadHtmlPreviewFonts } from "@/lib/community/html-preview-fonts"
import { applicationKey, assertApplicationOwner, captureApplicationOwner, useApplicationOwner } from "@/lib/application-owner"
@@ -12,8 +12,6 @@ import type { FileAttachment } from "@/lib/community/models/message"
import { useAttachmentDownload, attachmentDownloadStatusText } from "@/lib/community/attachment-download"
import { tid } from "@/lib/community/testids"
import { buttonVariants } from "@/components/ui/button"
-import { useNativeBackOwner } from "@/components/ui/native-back-layer"
-import { cn } from "@/lib/utils"
export function HtmlAttachmentPreview({ attachment }: { attachment: FileAttachment & { id: string } }) {
const owner = useApplicationOwner()
@@ -30,8 +28,6 @@ function HtmlPreviewDocument({ attachment }: { attachment: FileAttachment & { id
const [loaded, setLoaded] = useState(false)
const [status, setStatus] = useState<"loading" | "ready" | "error">("loading")
const [height, setHeight] = useState(320)
- const [expanded, setExpanded] = useState(false)
- const [inlineHeight, setInlineHeight] = useState(0)
const fontSheet = useQuery({
queryKey: applicationKey(owner, "html-preview-fonts", fonts), enabled: mounted && fonts.length > 0,
staleTime: Infinity, retry: false,
@@ -43,10 +39,9 @@ function HtmlPreviewDocument({ attachment }: { attachment: FileAttachment & { id
return css
},
}, owner.queryClient).data
- const root = useRef<HTMLDialogElement>(null)
+ const root = useRef<HTMLDivElement>(null)
const frame = useRef<HTMLIFrameElement>(null)
const ready = useRef(false)
- const expandButton = useRef<HTMLButtonElement>(null)
const download = useAttachmentDownload(attachment)
const id = attachment.id
const url = `${attachment.url}?preview=html`
@@ -94,42 +89,16 @@ function HtmlPreviewDocument({ attachment }: { attachment: FileAttachment & { id
return () => { clearTimeout(timeout); cancelAnimationFrame(themeFrame); window.removeEventListener("message", message) }
}, [mounted, error, resolvedTheme, fontSheet])
- function close() {
- const dialog = root.current
- if (!dialog) return
- dialog.close()
- dialog.show()
- setExpanded(false)
- expandButton.current?.focus()
- }
-
- useNativeBackOwner(() => expanded ? root.current : null, () => {
- close()
- return "requested"
- })
-
- function expand() {
- const dialog = root.current
- if (!dialog) return
- setInlineHeight(dialog.getBoundingClientRect().height)
- dialog.close()
- dialog.showModal()
- setExpanded(true)
- }
-
return (
- <div className="min-w-0" style={expanded ? { height: inlineHeight } : undefined}>
- <dialog
+ <div
ref={root}
- open
- role={expanded ? "dialog" : "group"}
- aria-modal={expanded || undefined}
+ role="group"
aria-label={attachment.name}
data-html-preview
data-testid={tid.htmlPreview(id)}
data-html-preview-status={status}
- onCancel={(event) => { event.preventDefault(); close() }}
- className="relative m-0 block w-full min-w-0 max-w-full overflow-hidden rounded-none border-0 bg-transparent p-0 text-foreground backdrop:bg-background/80 [&:modal]:fixed [&:modal]:inset-0 [&:modal]:m-auto [&:modal]:flex [&:modal]:h-[calc(100dvh-2rem)] [&:modal]:max-h-none [&:modal]:w-[calc(100vw-2rem)] [&:modal]:max-w-none [&:modal]:flex-col [&:modal]:bg-background"
+ className="relative m-0 block w-full min-w-0 max-w-full overflow-hidden rounded-none border-0 bg-transparent p-0 text-foreground"
+ style={!mounted && !error ? { height } : undefined}
>
<div role="group" aria-label="HTML preview actions" data-html-preview-actions className="absolute top-1.5 right-1.5 z-10 flex items-center">
<button
@@ -144,24 +113,14 @@ function HtmlPreviewDocument({ attachment }: { attachment: FileAttachment & { id
{download.state.status === "downloading" ? <LoaderCircle className="size-4 motion-safe:animate-spin" /> : <Download className="size-4" />}
<span className="sr-only" aria-live="polite">{attachmentDownloadStatusText(download.state)}</span>
</button>
- <button
- ref={expandButton}
- type="button"
- className={buttonVariants({ variant: "ghost", size: "icon" })}
- data-testid={expanded ? tid.htmlPreviewClose(id) : tid.htmlPreviewExpand(id)}
- aria-label={expanded ? "Close fullscreen preview" : "Expand HTML preview"}
- title={expanded ? "Close fullscreen preview" : "Expand HTML preview"}
- onClick={expanded ? close : expand}
- disabled={error && !expanded}
- >
- {expanded ? <X className="size-4" /> : <Expand className="size-4" />}
- </button>
</div>
{error ? (
<div role="status" className="p-4 text-sm text-muted-foreground">Preview unavailable. You can download this file.</div>
) : (
<>
- {status === "loading" && <div role="status" className="px-2 py-1 text-sm text-muted-foreground">Loading preview…</div>}
+ {status === "loading" && <div role="status" aria-label="Loading preview" className="pointer-events-none absolute inset-0 flex items-center justify-center text-muted-foreground">
+ <LoaderCircle aria-hidden="true" className="size-4 motion-safe:animate-spin" />
+ </div>}
{mounted && <iframe
ref={frame}
title={attachment.name}
@@ -171,12 +130,11 @@ function HtmlPreviewDocument({ attachment }: { attachment: FileAttachment & { id
referrerPolicy="no-referrer"
allow="camera 'none'; microphone 'none'; geolocation 'none'; clipboard-read 'none'; clipboard-write 'none'"
onLoad={() => setLoaded(true)}
- className={cn("block w-full border-0 bg-transparent scheme-light", expanded && "min-h-0 flex-1")}
- style={{ height: expanded ? undefined : height, colorScheme: loaded ? resolvedTheme === "dark" ? "dark" : "light" : undefined }}
+ className="block w-full border-0 bg-transparent scheme-light"
+ style={{ height, colorScheme: loaded ? resolvedTheme === "dark" ? "dark" : "light" : undefined }}
/>}
</>
)}
- </dialog>
</div>
)
}
diff --git a/src/web/src/lib/community/testids.ts b/src/web/src/lib/community/testids.ts
index 6c7e9e324..822d7a000 100644
--- a/src/web/src/lib/community/testids.ts
+++ b/src/web/src/lib/community/testids.ts
@@ -197,8 +197,6 @@ export const tid = {
threadOpenerImage: (index: number) => `community-thread-opener-image-${index}`,
htmlPreview: (id: string) => `community-html-preview-${id}`,
htmlPreviewFrame: (id: string) => `community-html-preview-frame-${id}`,
- htmlPreviewExpand: (id: string) => `community-html-preview-expand-${id}`,
- htmlPreviewClose: (id: string) => `community-html-preview-close-${id}`,
htmlPreviewDownload: (id: string) => `community-html-preview-download-${id}`,
attachmentCard: (name: string) => `community-attachment-card-${name}`,
attachmentPreviewSheet: "community-attachment-preview-sheet",
diff --git a/src/web/src/test/e2e-ui/20-community-attachment-thumbnails.spec.ts b/src/web/src/test/e2e-ui/20-community-attachment-thumbnails.spec.ts
index 7262f1c97..098d88dd0 100644
--- a/src/web/src/test/e2e-ui/20-community-attachment-thumbnails.spec.ts
+++ b/src/web/src/test/e2e-ui/20-community-attachment-thumbnails.spec.ts
@@ -967,12 +967,9 @@ test("HTML attachment markers render once with interactive isolated content acro
await content.getByRole("button", { name: "Add row" }).click()
await expect(content.locator("#count")).toHaveText("1")
await expect.poll(() => iframe.evaluate((element) => element.getBoundingClientRect().height)).toBeGreaterThan(beforeHeight)
- await message.getByTestId(tid.htmlPreviewExpand(attachmentId)).click()
- await expect(preview).toHaveAttribute("aria-modal", "true")
- await expect(content.locator("#count")).toHaveText("1")
- await message.getByTestId(tid.htmlPreviewClose(attachmentId)).click()
+ await expect(actions.getByRole("button")).toHaveCount(1)
+ await expect(actions.getByRole("button", { name: "Download interactive.html", exact: true })).toBeVisible()
await expect(preview).not.toHaveAttribute("aria-modal", "true")
- await expect(content.locator("#count")).toHaveText("1")
const previewUrl = `/api/community/channels/${channelId}/attachments/${attachmentId}?preview=html`
const direct = await page.request.get(previewUrl)
@@ -989,10 +986,9 @@ test("HTML attachment markers render once with interactive isolated content acro
await expect(readerPreview).toHaveAttribute("data-html-preview-status", "ready")
await expect(readerPreview.getByTestId(tid.htmlPreviewFrame(attachmentId)).contentFrame().getByRole("button", { name: "Add row" })).toBeVisible()
await expect(readerPreview.getByRole("group", { name: "HTML preview actions" })).toHaveCSS("opacity", "1")
- await expect(readerPreview.getByTestId(tid.htmlPreviewExpand(attachmentId))).toHaveCSS("width", "44px")
- await readerPreview.getByTestId(tid.htmlPreviewExpand(attachmentId)).tap()
- await expect(readerPreview).toHaveAttribute("aria-modal", "true")
- await readerPreview.getByTestId(tid.htmlPreviewClose(attachmentId)).tap()
+ await expect(readerPreview.getByRole("group", { name: "HTML preview actions" }).getByRole("button")).toHaveCount(1)
+ await expect(readerPreview.getByTestId(tid.htmlPreviewDownload(attachmentId))).toHaveCSS("width", "24px")
+ await expect(readerPreview.getByTestId(tid.htmlPreviewDownload(attachmentId))).toHaveCSS("height", "24px")
await expect(readerPreview).not.toHaveAttribute("aria-modal", "true")
await expect(readerPreview.getByTestId(tid.htmlPreviewFrame(attachmentId)).contentFrame().locator("#count")).toHaveText("0")
const { page: outsider } = await actors.asUser("carol")
@@ -1022,10 +1018,17 @@ test("HTML attachment markers render once with interactive isolated content acro
await transparentPreview.scrollIntoViewIfNeeded()
await expect.poll(heldPreview.held).toBeGreaterThan(0)
await expect(transparentPreview).toHaveAttribute("data-html-preview-status", "loading")
+ const loadingStatus = transparentPreview.getByRole("status", { name: "Loading preview" })
+ await expect(loadingStatus).toBeVisible()
+ const region = await boundingRect(transparentPreview)
+ const indicator = await boundingRect(loadingStatus.locator("svg"))
+ expect(Math.abs(indicator.x + indicator.width / 2 - region.x - region.width / 2)).toBeLessThanOrEqual(1)
+ expect(Math.abs(indicator.y + indicator.height / 2 - region.y - region.height / 2)).toBeLessThanOrEqual(1)
await expect(transparentFrame).toHaveCSS("color-scheme", "light")
loading = await captureCanvas("transparent-canvas-dark-host-loading.png")
} finally { await heldPreview.release() }
await expect(transparentPreview).toHaveAttribute("data-html-preview-status", "ready")
+ await expect(transparentPreview.getByRole("status", { name: "Loading preview" })).toHaveCount(0)
await expect(transparentFrame).toHaveCSS("color-scheme", "dark")
const transparentContent = transparentFrame.contentFrame()
const originalTransparentFrame = await transparentFrame.elementHandle()
@@ -1077,17 +1080,12 @@ test("HTML attachment markers render once with interactive isolated content acro
await transparentPreview.hover()
await expect(transparentActions).toHaveCSS("opacity", "1")
await expect(transparentActions).toHaveCSS("pointer-events", "auto")
- await transparentPreview.getByTestId(tid.htmlPreviewExpand(transparentId)).click()
- await expect(transparentPreview).toHaveAttribute("aria-modal", "true")
- const fullscreen = await transparentPixels(`transparent-canvas-${mode.toLowerCase()}-fullscreen.png`)
- await transparentPreview.getByTestId(tid.htmlPreviewClose(transparentId)).click()
+ await expect(transparentActions.getByRole("button")).toHaveCount(1)
await expect(transparentPreview).not.toHaveAttribute("aria-modal", "true")
await expect(transparentContent.locator("#state")).toHaveValue("retained edit")
- canvasSamples.push({ mode, inline, fullscreen })
- }
- for (const phase of ["inline", "fullscreen"] as const) {
- expect(canvasSamples[1]![phase].canvas.reduce((sum, value) => sum + value, 0)).toBeLessThan(canvasSamples[0]![phase].canvas.reduce((sum, value) => sum + value, 0))
+ canvasSamples.push({ mode, inline })
}
+ expect(canvasSamples[1]!.inline.canvas.reduce((sum, value) => sum + value, 0)).toBeLessThan(canvasSamples[0]!.inline.canvas.reduce((sum, value) => sum + value, 0))
expect(loading.canvas.reduce((sum, value) => sum + value, 0)).toBeLessThan(canvasSamples[0]!.inline.canvas.reduce((sum, value) => sum + value, 0))
await appearance("Light")
await expect(transparentContent.locator("html")).toHaveCSS("color-scheme", "light dark")