Shared task board where people and AI coding agents work as teammates. Source-available, self-hostable.
Go
MUL-8700 fix(views): HTML viewer Fit scales a wider document down to fit (#10055)
Jiayuan Zhang6644bf019be0
diff --git a/packages/views/attachments/attachment-preview-page.test.tsx b/packages/views/attachments/attachment-preview-page.test.tsxindex 5f666c9e69..14e8220650 100644--- a/packages/views/attachments/attachment-preview-page.test.tsx+++ b/packages/views/attachments/attachment-preview-page.test.tsx@@ -10,6 +10,7 @@ import { AttachmentPreviewPage, HTML_PREVIEW_ADDRESS_KEY } from "./attachment-primport { hashString } from "../editor/utils/hash-string";import { buildScrollBridge } from "../editor/utils/iframe-scroll-bridge";import { withFragmentNavShim } from "../editor/utils/iframe-fragment-nav";+import { withWidthBridge } from "../editor/utils/iframe-width-bridge";import { withLocationBridge } from "../editor/utils/iframe-location-bridge";const htmlText = "<html><body><h1>Report</h1></body></html>";@@ -109,7 +110,7 @@ describe("AttachmentPreviewPage", () => {</ScrollRestorationProvider>,);const iframe = await screen.findByTitle("report.html");- expect(iframe.getAttribute("srcdoc")).toContain(buildScrollBridge(hashString(htmlText)));+ expect(iframe.getAttribute("srcdoc")).toContain(buildScrollBridge(hashString(withWidthBridge(htmlText))));// The iframe stays inside the sandbox the viewer uses.expect(iframe.getAttribute("sandbox")).toBe("allow-scripts");expect(adapter.registerExternalSource).toHaveBeenCalledWith(@@ -128,7 +129,7 @@ describe("AttachmentPreviewPage", () => {const iframe = await screen.findByTitle("report.html");// The address bridge and the fragment-nav shim, but no scroll bridge.expect(iframe.getAttribute("srcdoc")).toBe(- withLocationBridge(withFragmentNavShim(htmlText), ""),+ withLocationBridge(withFragmentNavShim(withWidthBridge(htmlText)), ""),);});@@ -136,7 +137,7 @@ describe("AttachmentPreviewPage", () => {renderPage(<AttachmentPreviewPage attachmentId="att-1" initialAddress="?s=ia" />);const iframe = await screen.findByTitle("report.html");expect(iframe.getAttribute("srcdoc")).toBe(- withLocationBridge(withFragmentNavShim(htmlText), "?s=ia"),+ withLocationBridge(withFragmentNavShim(withWidthBridge(htmlText)), "?s=ia"),);expect(screen.getByRole("textbox", { name: "Address" })).toHaveValue("?s=ia");});@@ -155,7 +156,7 @@ describe("AttachmentPreviewPage", () => {);const iframe = await screen.findByTitle("report.html");expect(iframe.getAttribute("srcdoc")).toBe(- withLocationBridge(withFragmentNavShim(htmlText), "?s=kept"),+ withLocationBridge(withFragmentNavShim(withWidthBridge(htmlText)), "?s=kept"),);const input = screen.getByRole("textbox", { name: "Address" });diff --git a/packages/views/editor/attachment-preview-modal.test.tsx b/packages/views/editor/attachment-preview-modal.test.tsxindex 2511522970..b1c77715fa 100644--- a/packages/views/editor/attachment-preview-modal.test.tsx+++ b/packages/views/editor/attachment-preview-modal.test.tsx@@ -177,6 +177,7 @@ import {useAttachmentPreview,} from "./attachment-preview-modal";import { withFragmentNavShim } from "./utils/iframe-fragment-nav";+import { withWidthBridge } from "./utils/iframe-width-bridge";import { withLocationBridge } from "./utils/iframe-location-bridge";import { renderHook, act as hookAct } from "@testing-library/react";@@ -337,11 +338,12 @@ describe("AttachmentPreviewModal — dispatch", () => {// (MUL-2330). The combination with `allow-same-origin` would defeat// the sandbox, so this assertion must stay exact.expect(frame?.getAttribute("sandbox")).toBe("allow-scripts");- // srcdoc carries the original HTML between the address bridge in+ // srcdoc carries the original HTML (with the width bridge,+ // utils/iframe-width-bridge.ts) between the address bridge in// front (utils/iframe-location-bridge.ts) and the fragment-nav shim// appended at the end (utils/iframe-fragment-nav.ts).expect(frame?.getAttribute("srcdoc")).toBe(- withLocationBridge(withFragmentNavShim("<p>hi</p>"), ""),+ withLocationBridge(withFragmentNavShim(withWidthBridge("<p>hi</p>")), ""),);});});@@ -360,7 +362,7 @@ describe("AttachmentPreviewModal — dispatch", () => {const frame = document.querySelector("iframe[sandbox]") as HTMLIFrameElement;expect(frame.getAttribute("srcdoc")).toBe(- withLocationBridge(withFragmentNavShim("<p>hi</p>"), "?s=overview"),+ withLocationBridge(withFragmentNavShim(withWidthBridge("<p>hi</p>")), "?s=overview"),);expect((input as HTMLInputElement).value).toBe("?s=overview");});@@ -385,7 +387,7 @@ describe("AttachmentPreviewModal — dispatch", () => {expect(screen.getByLabelText("Address")).toHaveValue("?s=ia");expect(document.querySelector("iframe[sandbox]")?.getAttribute("srcdoc")).toBe(- withLocationBridge(withFragmentNavShim("<p>hi</p>"), "?s=ia"),+ withLocationBridge(withFragmentNavShim(withWidthBridge("<p>hi</p>")), "?s=ia"),);});diff --git a/packages/views/editor/attachment-preview-modal.tsx b/packages/views/editor/attachment-preview-modal.tsxindex f6c00f5249..762a2ce6ad 100644--- a/packages/views/editor/attachment-preview-modal.tsx+++ b/packages/views/editor/attachment-preview-modal.tsx@@ -107,6 +107,7 @@ import {HtmlViewportFrame,type HtmlViewport,} from "./html-viewport-frame";+import { withWidthBridge } from "./utils/iframe-width-bridge";// Preview source — full attachment, or URL-only (media types only)//@@ -1461,7 +1462,7 @@ function PreviewContent({) : (<HtmlViewportFrame viewport={view.htmlViewport}>{view.renderHtmlFrame({- html: text,+ html: withWidthBridge(text),title: state.filename,location: view.htmlLocation,})}diff --git a/packages/views/editor/html-viewport-frame.test.tsx b/packages/views/editor/html-viewport-frame.test.tsxindex 2869f9254a..fd1d3be5ae 100644--- a/packages/views/editor/html-viewport-frame.test.tsx+++ b/packages/views/editor/html-viewport-frame.test.tsx@@ -1,7 +1,39 @@import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";-import { screen } from "@testing-library/react";+import { act, screen } from "@testing-library/react";import { renderWithI18n } from "../test/i18n";-import { fitViewport, HtmlViewportFrame } from "./html-viewport-frame";+import { fitViewport, HtmlViewportFrame, nextFitAttempt } from "./html-viewport-frame";+import { HTML_PREVIEW_WIDTH_KEY } from "./utils/iframe-width-bridge";++describe("nextFitAttempt", () => {+ const at = (viewport: number, needed: number, doc = "a") => ({ doc, viewport, needed });+ const trying = { doc: "a", stage: 1000, width: 1080, failed: false };++ it("starts an attempt only from an overflow measured at the stage's width", () => {+ expect(nextFitAttempt(null, at(1000, 1080), 1000)).toEqual(trying);+ expect(nextFitAttempt(null, at(1000, 1000), 1000)).toBeNull();+ expect(nextFitAttempt(null, at(1440, 1600), 1000)).toBeNull();+ });++ it("keeps an attempt the document fits, and fails one it still overflows", () => {+ expect(nextFitAttempt(trying, at(1080, 1080), 1000)).toBe(trying);+ expect(nextFitAttempt(trying, at(1080, 1128), 1000)).toEqual({ ...trying, failed: true });+ });++ it("ignores reports measured at any other width while trying", () => {+ expect(nextFitAttempt(trying, at(1000, 1080), 1000)).toBe(trying);+ expect(nextFitAttempt(trying, at(1440, 1600), 1000)).toBe(trying);+ });++ it("never retries a failed attempt for the same document and stage", () => {+ const failed = { ...trying, failed: true };+ expect(nextFitAttempt(failed, at(1000, 1080), 1000)).toBe(failed);+ });++ it("starts over for a new document or stage width", () => {+ expect(nextFitAttempt(trying, at(1000, 1200, "b"), 1000)).toEqual({ ...trying, doc: "b", width: 1200 });+ expect(nextFitAttempt(trying, at(1100, 1100), 1100)).toBeNull();+ });+});describe("fitViewport", () => {it("keeps the device width and scales it down into a narrower area", () => {@@ -60,6 +92,121 @@ describe("HtmlViewportFrame", () => {expect(screen.getByText("390 × 800")).toBeTruthy();});+ function report(data: Record<string, unknown>, source = screen.getByTitle("doc")) {+ act(() => {+ window.dispatchEvent(+ new MessageEvent("message", {+ data: { [HTML_PREVIEW_WIDTH_KEY]: 1, type: "width", ...data },+ source: (source as HTMLIFrameElement).contentWindow,+ }),+ );+ });+ }++ describe("fit", () => {+ it("lays a document wider than the stage out at its own width and scales it to fit", () => {+ renderWithI18n(<HtmlViewportFrame viewport="fill">{frame}</HtmlViewportFrame>);+ report({ doc: "a", viewport: 1100, needed: 1320 });++ expect(screen.getByTestId("html-viewport").style.width).toBe("1100px");+ const layout = screen.getByTitle("doc").parentElement!;+ expect(layout.style.width).toBe("1320px");+ expect(layout.style.transform).toBe(`scale(${1100 / 1320})`);+ expect(screen.getByText(/1320 × 960/)).toHaveTextContent("1320 × 960 · Scaled to 83%");+ });++ it("keeps the width once the widened document stops overflowing", () => {+ renderWithI18n(<HtmlViewportFrame viewport="fill">{frame}</HtmlViewportFrame>);+ report({ doc: "a", viewport: 1100, needed: 1320 });+ report({ doc: "a", viewport: 1320, needed: 1320 });++ expect(screen.getByTitle("doc").parentElement!.style.width).toBe("1320px");+ });++ it("fills the stage again when the widened document still overflows", () => {+ // A `width: 100%` box with padding overflows by the same amount at+ // any width: widening can only chase it.+ renderWithI18n(<HtmlViewportFrame viewport="fill">{frame}</HtmlViewportFrame>);+ report({ doc: "a", viewport: 1100, needed: 1148 });+ report({ doc: "a", viewport: 1148, needed: 1196 });+ report({ doc: "a", viewport: 1100, needed: 1148 });++ expect(screen.getByTestId("html-viewport").style.width).toBe("100%");+ expect(screen.queryByText(/×/)).toBeNull();+ });++ it("starts over for a new document", () => {+ renderWithI18n(<HtmlViewportFrame viewport="fill">{frame}</HtmlViewportFrame>);+ report({ doc: "a", viewport: 1100, needed: 1320 });+ report({ doc: "b", viewport: 1320, needed: 1320 });++ expect(screen.getByTestId("html-viewport").style.width).toBe("100%");+ expect(screen.queryByText(/×/)).toBeNull();+ });++ it("fills the stage for a document wider than twice the desktop width", () => {+ renderWithI18n(<HtmlViewportFrame viewport="fill">{frame}</HtmlViewportFrame>);+ report({ doc: "a", viewport: 1100, needed: 9000 });++ expect(screen.getByTestId("html-viewport").style.width).toBe("100%");+ });++ it("does not carry a device width's layout back into Fit", () => {+ const { rerender } = renderWithI18n(+ <HtmlViewportFrame viewport="fill">{frame}</HtmlViewportFrame>,+ );+ report({ doc: "a", viewport: 1100, needed: 1100 });+ rerender(<HtmlViewportFrame viewport="desktop">{frame}</HtmlViewportFrame>);+ // Past a breakpoint the document grows wider than its viewport.+ report({ doc: "a", viewport: 1440, needed: 1600 });+ rerender(<HtmlViewportFrame viewport="fill">{frame}</HtmlViewportFrame>);+ report({ doc: "a", viewport: 1440, needed: 1600 });++ expect(screen.getByTestId("html-viewport").style.width).toBe("100%");+ expect(screen.queryByText(/×/)).toBeNull();+ });++ it("forgets a Fit width on leaving Fit, and measures again on return", () => {+ const { rerender } = renderWithI18n(+ <HtmlViewportFrame viewport="fill">{frame}</HtmlViewportFrame>,+ );+ report({ doc: "a", viewport: 1100, needed: 1320 });+ rerender(<HtmlViewportFrame viewport="tablet">{frame}</HtmlViewportFrame>);+ const measure = vi.spyOn(+ (screen.getByTitle("doc") as HTMLIFrameElement).contentWindow!,+ "postMessage",+ );+ rerender(<HtmlViewportFrame viewport="fill">{frame}</HtmlViewportFrame>);++ expect(screen.getByTestId("html-viewport").style.width).toBe("100%");+ expect(measure).toHaveBeenCalledWith(+ { [HTML_PREVIEW_WIDTH_KEY]: 1, type: "measure" },+ "*",+ );+ report({ doc: "a", viewport: 1100, needed: 1320 });+ expect(screen.getByTitle("doc").parentElement!.style.width).toBe("1320px");+ });++ it("ignores reports from any other window", () => {+ renderWithI18n(+ <>+ <HtmlViewportFrame viewport="fill">{frame}</HtmlViewportFrame>+ <iframe title="other" />+ </>,+ );+ report({ doc: "a", viewport: 1100, needed: 1320 }, screen.getByTitle("other"));++ expect(screen.getByTestId("html-viewport").style.width).toBe("100%");+ });++ it("leaves device widths alone", () => {+ renderWithI18n(<HtmlViewportFrame viewport="phone">{frame}</HtmlViewportFrame>);+ report({ doc: "a", viewport: 390, needed: 600 });++ expect(screen.getByTestId("html-viewport").style.width).toBe("390px");+ });+ });+it("localizes the scale", () => {renderWithI18n(<HtmlViewportFrame viewport="desktop">{frame}</HtmlViewportFrame>, {locale: "zh-Hans",diff --git a/packages/views/editor/html-viewport-frame.tsx b/packages/views/editor/html-viewport-frame.tsxindex e5efbe02c2..f3a3ae1e7a 100644--- a/packages/views/editor/html-viewport-frame.tsx+++ b/packages/views/editor/html-viewport-frame.tsx@@ -4,8 +4,13 @@* HtmlViewportFrame — lays an HTML attachment's iframe out at a chosen* viewport width, for the viewer's html kind.*- * - fill : the iframe takes the whole stage, as the page would in a- * browser window that size. The default.+ * - fill : "Fit". The iframe takes the whole stage, as the page would in+ * a browser window that size. A document wider than the stage+ * (the width bridge in utils/iframe-width-bridge.ts reports it)+ * is laid out at its own width and scaled down to fit, so+ * nothing hides past the right edge — when that width holds+ * it; a document that only grows with its viewport keeps+ * filling the stage. The default.* - desktop / tablet / phone : the iframe is exactly 1440 / 768 / 390 CSS px* wide, so the document's media queries see that device. When* the stage is narrower the frame scales down to fit — layout@@ -13,12 +18,18 @@* caption says by how much. Height always fills the stage.** The iframe itself is the caller's: the viewer and the full-page preview- * wire different ones, and this only owns the box around it.+ * wire different ones, and this only owns the box around it. Fit only+ * scales when the caller's document carries the width bridge.*/-import { useLayoutEffect, useState, type ReactNode } from "react";+import { useEffect, useLayoutEffect, useState, type ReactNode } from "react";import { cn } from "@multica/ui/lib/utils";import { useT } from "../i18n";+import {+ HTML_PREVIEW_WIDTH_KEY,+ readHtmlPreviewWidthMessage,+ type HtmlPreviewWidthMessage,+} from "./utils/iframe-width-bridge";export type HtmlViewport = "fill" | "desktop" | "tablet" | "phone";@@ -35,6 +46,9 @@ export const VIEWPORT_WIDTHS: Record<Exclude<HtmlViewport, "fill">, number> = {phone: 390,};+/** The widest layout Fit will scale down from; past it the document fills the stage and scrolls. */+export const FIT_MAX_WIDTH = VIEWPORT_WIDTHS.desktop * 2;+export interface ViewportFit {/** CSS px the document lays out in. */width: number;@@ -77,6 +91,80 @@ function useLayoutSize(node: HTMLElement | null) {return size;}+/**+ * Fit's one try at widening a document, for one document at one stage width.+ * `failed` once the document still overflowed at `width`: its overflow grows+ * with the viewport (a `width: 100%` box with padding, a breakpoint that+ * jumps wider), so widening cannot settle it and Fit fills the stage instead.+ */+export interface FitAttempt {+ doc: string;+ stage: number;+ width: number;+ failed: boolean;+}++// Widths are whole CSS px on both sides, but the stage's offsetWidth and the+// frame's innerWidth may round a fractional box differently.+const near = (a: number, b: number) => Math.abs(a - b) <= 1;++/**+ * The attempt after a width report. Only a report measured at the stage's+ * own width starts an attempt; only one measured at the attempt's width+ * settles it. Anything else — a device width's layout, a report in flight+ * while the frame resizes — is not about the layout Fit is deciding on.+ */+export function nextFitAttempt(+ previous: FitAttempt | null,+ report: HtmlPreviewWidthMessage,+ stage: number,+): FitAttempt | null {+ const current =+ previous?.doc === report.doc && previous.stage === stage ? previous : null;+ if (!current) {+ if (!near(report.viewport, stage)) return null;+ if (report.needed <= report.viewport || report.needed > FIT_MAX_WIDTH) return null;+ return { doc: report.doc, stage, width: report.needed, failed: false };+ }+ if (current.failed || !near(report.viewport, current.width)) return current;+ return report.needed > report.viewport ? { ...current, failed: true } : current;+}++// The width Fit lays the document out at when that is wider than the stage,+// from the width bridge's reports; null fills the stage. Leaving Fit forgets+// the attempt, so coming back measures afresh against the stage.+function useFitWidth(area: HTMLElement | null, active: boolean, stage: number | null) {+ const [attempt, setAttempt] = useState<FitAttempt | null>(null);+ const [wasActive, setWasActive] = useState(active);+ if (wasActive !== active) {+ setWasActive(active);+ setAttempt(null);+ }++ useEffect(() => {+ if (!area || !active || stage === null) return;+ const frame = () => area.querySelector("iframe")?.contentWindow ?? null;+ const onMessage = (event: MessageEvent) => {+ if (!event.source || event.source !== frame()) return;+ const report = readHtmlPreviewWidthMessage(event.data);+ if (report) setAttempt((previous) => nextFitAttempt(previous, report, stage));+ };+ window.addEventListener("message", onMessage);+ // The frame may already be at the stage's width (back from a device+ // width the same size), and then no resize inside it reports.+ frame()?.postMessage({ [HTML_PREVIEW_WIDTH_KEY]: 1, type: "measure" }, "*");+ return () => window.removeEventListener("message", onMessage);+ }, [area, active, stage]);++ return active &&+ attempt &&+ !attempt.failed &&+ attempt.stage === stage &&+ attempt.width > attempt.stage+ ? attempt.width+ : null;+}+export function HtmlViewportFrame({viewport,children,@@ -88,39 +176,41 @@ export function HtmlViewportFrame({const { t } = useT("editor");const [area, setArea] = useState<HTMLDivElement | null>(null);const size = useLayoutSize(area);+ const fitWidth = useFitWidth(area, viewport === "fill", size?.width || null);- const deviceWidth = viewport === "fill" ? null : VIEWPORT_WIDTHS[viewport];+ // The width the document lays out at; null fills the stage.+ const layoutWidth = viewport === "fill" ? fitWidth : VIEWPORT_WIDTHS[viewport];// Until the area has a size (first layout, or a host without layout such// as a test DOM) a device frame shows unscaled at full height.const fit =- deviceWidth !== null && size && size.width > 0- ? fitViewport(size, deviceWidth)+ layoutWidth !== null && size && size.width > 0+ ? fitViewport(size, layoutWidth): null;const percent = fit ? Math.round(fit.scale * 100) : 100;// One element tree for every viewport, so switching only resizes the// iframe — it never remounts, and the document keeps its state.return (- <div className={cn("flex h-full flex-col", deviceWidth === null ? "pb-4" : "pb-2")}>+ <div className={cn("flex h-full flex-col", layoutWidth === null ? "pb-4" : "pb-2")}><div ref={setArea} className="relative min-h-0 flex-1">{/* The visible box is the scaled size; inside it the frame lays out- at full device size and a transform shrinks it to fit. */}+ at its full layout width and a transform shrinks it to fit. */}<divclassName="mx-auto h-full max-w-full overflow-hidden rounded-lg"style={{width:- deviceWidth === null+ layoutWidth === null? "100%": fit- ? deviceWidth * fit.scale- : deviceWidth,+ ? layoutWidth * fit.scale+ : layoutWidth,}}data-testid="html-viewport"><divclassName="h-full w-full"style={- deviceWidth === null+ layoutWidth === null? undefined: fit? {@@ -129,16 +219,16 @@ export function HtmlViewportFrame({transform: fit.scale < 1 ? `scale(${fit.scale})` : undefined,transformOrigin: "top left",}- : { width: deviceWidth }+ : { width: layoutWidth }}>{children}</div></div></div>- {deviceWidth !== null && (+ {layoutWidth !== null && (<p className="dark shrink-0 pt-2 text-center text-caption tabular-nums text-muted-foreground">- {fit ? `${fit.width} × ${fit.height}` : deviceWidth}+ {fit ? `${fit.width} × ${fit.height}` : layoutWidth}{percent < 100 && (<>{" · "}diff --git a/packages/views/editor/utils/iframe-width-bridge.test.ts b/packages/views/editor/utils/iframe-width-bridge.test.tsnew file mode 100644index 0000000000..f458cd3e97--- /dev/null+++ b/packages/views/editor/utils/iframe-width-bridge.test.ts@@ -0,0 +1,95 @@+import { afterEach, describe, expect, it, vi } from "vitest";+import {+ __WIDTH_BRIDGE_SCRIPT__,+ HTML_PREVIEW_WIDTH_KEY,+ readHtmlPreviewWidthMessage,+ withWidthBridge,+} from "./iframe-width-bridge";++const K = HTML_PREVIEW_WIDTH_KEY;++describe("withWidthBridge", () => {+ it("appends the bridge after the author's markup, leaving a doctype first", () => {+ const html = "<!doctype html><p>hi</p>";+ expect(withWidthBridge(html)).toBe(`${html}<script>${__WIDTH_BRIDGE_SCRIPT__}</script>`);+ });+});++describe("readHtmlPreviewWidthMessage", () => {+ it("reads a width report", () => {+ expect(+ readHtmlPreviewWidthMessage({ [K]: 1, type: "width", doc: "abc", viewport: 1000, needed: 1080 }),+ ).toEqual({ doc: "abc", viewport: 1000, needed: 1080 });+ });++ it.each([+ ["not an object", "width"],+ ["no marker", { type: "width", doc: "a", viewport: 1, needed: 1 }],+ ["another type", { [K]: 1, type: "location", doc: "a", viewport: 1, needed: 1 }],+ ["no doc", { [K]: 1, type: "width", viewport: 1, needed: 1 }],+ ["a long doc", { [K]: 1, type: "width", doc: "x".repeat(33), viewport: 1, needed: 1 }],+ ["a string width", { [K]: 1, type: "width", doc: "a", viewport: "1000", needed: 1 }],+ ["a zero width", { [K]: 1, type: "width", doc: "a", viewport: 0, needed: 1 }],+ ["an unbounded width", { [K]: 1, type: "width", doc: "a", viewport: 1, needed: 1e9 }],+ ["a non-finite width", { [K]: 1, type: "width", doc: "a", viewport: 1, needed: Infinity }],+ ])("drops %s", (_, data) => {+ expect(readHtmlPreviewWidthMessage(data)).toBeNull();+ });+});++// Evaluated against the current jsdom document, whose `parent` is itself;+// postMessage is stubbed to capture the reports. jsdom has no layout, so the+// widths are stubbed on the root element.+describe("the bridge script", () => {+ afterEach(() => {+ vi.restoreAllMocks();+ document.documentElement.style.overflowX = "";+ });++ let listeners: Array<[string, EventListener]> = [];++ function run(layout: { viewport: number; client: number; scroll: number }) {+ const postMessage = vi.spyOn(window, "postMessage").mockImplementation(() => {});+ vi.spyOn(window, "innerWidth", "get").mockReturnValue(layout.viewport);+ vi.spyOn(document.documentElement, "clientWidth", "get").mockReturnValue(layout.client);+ vi.spyOn(document.documentElement, "scrollWidth", "get").mockReturnValue(layout.scroll);+ listeners = [];+ vi.spyOn(window, "addEventListener").mockImplementation((type: string, listener) => {+ listeners.push([type, listener as EventListener]);+ });+ new Function(__WIDTH_BRIDGE_SCRIPT__)();+ return postMessage.mock.calls.map(([m]) => readHtmlPreviewWidthMessage(m));+ }++ function fire(type: string, event: Event) {+ for (const [t, listener] of listeners) if (t === type) listener(event);+ }++ it("reports again only when the layout changed, unless the parent asks", () => {+ run({ viewport: 1000, client: 1000, scroll: 1000 });+ const postMessage = vi.mocked(window.postMessage);+ fire("resize", new Event("resize"));+ expect(postMessage).toHaveBeenCalledTimes(1);++ fire("message", new MessageEvent("message", { data: { [K]: 1, type: "measure" }, source: window }));+ expect(postMessage).toHaveBeenCalledTimes(2);+ fire("message", new MessageEvent("message", { data: { [K]: 1, type: "measure" }, source: null }));+ expect(postMessage).toHaveBeenCalledTimes(2);+ });++ it("reports a document that fits as needing its viewport", () => {+ const [report] = run({ viewport: 1000, client: 1000, scroll: 1000 });+ expect(report).toMatchObject({ viewport: 1000, needed: 1000 });+ });++ it("reports the overflow on top of the viewport, scrollbar gutter included", () => {+ const [report] = run({ viewport: 1000, client: 985, scroll: 1065 });+ expect(report).toMatchObject({ viewport: 1000, needed: 1080 });+ });++ it("takes a document that clips its own overflow at its word", () => {+ document.documentElement.style.overflowX = "hidden";+ const [report] = run({ viewport: 1000, client: 1000, scroll: 1400 });+ expect(report).toMatchObject({ viewport: 1000, needed: 1000 });+ });+});diff --git a/packages/views/editor/utils/iframe-width-bridge.ts b/packages/views/editor/utils/iframe-width-bridge.tsnew file mode 100644index 0000000000..1cdb43edc6--- /dev/null+++ b/packages/views/editor/utils/iframe-width-bridge.ts@@ -0,0 +1,84 @@+/**+ * Width bridge for the HTML attachment viewer's Fit viewport (MUL-8700).+ *+ * Fit lays the document out at the stage's width. A document built for a+ * wider screen — a fixed-width table, a grid of min-width cards — overflows+ * that width and would scroll sideways, so Fit needs to know how wide the+ * document actually is to lay it out there and scale it down instead. The+ * iframe is an opaque origin, so the parent cannot read the document's+ * `scrollWidth`; this script, appended to the author's markup, reports it.+ *+ * Each report carries the frame's own width (`viewport`, `innerWidth`) and+ * the width the document needs (`needed`): the viewport plus whatever the+ * content overflows it by, so a classic scrollbar's gutter is counted. A+ * document that clips its own overflow (`overflow-x: hidden` / `clip` on+ * the root or body — the usual guard for decorative bleed) needs no more+ * than its viewport. `doc` is fresh for every document load, so the parent+ * can forget a width learned from a document that is gone. It reports on+ * load, resize and layout changes, and on a `measure` request from the+ * parent even when nothing changed.+ *+ * It runs in the iframe's opaque origin with the capabilities the author's+ * scripts already have. The parent treats every message as untrusted (see+ * readHtmlPreviewWidthMessage).+ */++/** Marker on every bridge message. */+export const HTML_PREVIEW_WIDTH_KEY = "__multicaHtmlWidth";++/** Upper bound on a reported width; anything larger is not a width we keep. */+const MAX_REPORTED_WIDTH = 100_000;++const SCRIPT = [+ "(function(){",+ `var K=${JSON.stringify(HTML_PREVIEW_WIDTH_KEY)},D=document.documentElement,`,+ "ID=Math.random().toString(36).slice(2),last='';",+ "function clips(el){if(!el)return false;var o=getComputedStyle(el).overflowX;return o==='hidden'||o==='clip'}",+ "function measure(force){var b=document.body,vw=window.innerWidth,cw=D.clientWidth;",+ "var sw=clips(D)||clips(b)?cw:Math.max(D.scrollWidth,b?b.scrollWidth:0);",+ "var need=vw+Math.max(0,Math.ceil(sw-cw));var key=vw+'/'+need;if(!force&&key===last)return;last=key;",+ "var m={type:'width',doc:ID,viewport:vw,needed:need};m[K]=1;try{parent.postMessage(m,'*')}catch(_){}}",+ "function report(){measure(false)}",+ "report();window.addEventListener('load',report);window.addEventListener('resize',report);",+ "if(document.fonts&&document.fonts.ready)document.fonts.ready.then(report);",+ "if(typeof ResizeObserver==='function'){var ro=new ResizeObserver(report);ro.observe(D);if(document.body)ro.observe(document.body)}",+ "window.addEventListener('message',function(e){if(e.source!==parent)return;var d=e.data;",+ "if(d&&d[K]===1&&d.type==='measure')measure(true)});",+ "})();",+].join("");++/** Exposed for tests so they can evaluate the script in jsdom. */+export const __WIDTH_BRIDGE_SCRIPT__ = SCRIPT;++/** The document with the width bridge appended after the author's markup. */+export function withWidthBridge(html: string): string {+ return `${html}<script>${SCRIPT}</script>`;+}++export interface HtmlPreviewWidthMessage {+ /** Identifies the document load the report came from. */+ doc: string;+ /** The frame's width, in the document's CSS px. */+ viewport: number;+ /** The width the document needs to show without scrolling sideways. */+ needed: number;+}++function isWidth(value: unknown): value is number {+ return typeof value === "number" && Number.isFinite(value) && value > 0 && value <= MAX_REPORTED_WIDTH;+}++/**+ * Parses a bridge message. Returns null for anything that is not one; the+ * sandboxed document can post whatever it likes, so only a short id and two+ * bounded widths get through.+ */+export function readHtmlPreviewWidthMessage(data: unknown): HtmlPreviewWidthMessage | null {+ if (typeof data !== "object" || data === null) return null;+ const record = data as Record<string, unknown>;+ if (record[HTML_PREVIEW_WIDTH_KEY] !== 1 || record.type !== "width") return null;+ const { doc, viewport, needed } = record;+ if (typeof doc !== "string" || doc.length === 0 || doc.length > 32) return null;+ if (!isWidth(viewport) || !isWidth(needed)) return null;+ return { doc, viewport, needed };+}