Shared task board where people and AI coding agents work as teammates. Source-available, self-hostable.
Go
MUL-9460: fix HTML preview fragment navigation (#10797)
Multica Eve2a6cd018486f
diff --git a/e2e/html-preview-fragment-nav.spec.ts b/e2e/html-preview-fragment-nav.spec.tsnew file mode 100644index 0000000000..9b6f60b7a4--- /dev/null+++ b/e2e/html-preview-fragment-nav.spec.ts@@ -0,0 +1,235 @@+import { expect, test, type Page } from "@playwright/test";+import { createTestApi, loginAsDefault } from "./helpers";+import type { TestApiClient } from "./fixtures";+import { withFragmentNavShim } from "../packages/views/editor/utils/iframe-fragment-nav";+import { withLocationBridge } from "../packages/views/editor/utils/iframe-location-bridge";++const apiBase = process.env.NEXT_PUBLIC_API_URL || `http://localhost:${process.env.PORT || "8080"}`;+const report = `<!doctype html><html lang="en"><head><title>Fragment report</title>+<style>+body { margin: 40px; font: 18px system-ui; color: #172033; background: #fff; }+.view { display: none; padding: 24px; border: 1px solid #b9c8de; border-radius: 12px; }+.view:target, body:not(:has(.view:target)) #page-1 { display: block; }+a { display: inline-block; margin-right: 24px; color: #194eb7; }+</style></head><body>+<section class="view" id="page-1"><h1>Report: page 1</h1>+<p>Fictional report for fragment navigation verification.</p>+<a href="#page-2">Next</a><a href="#detail">Details</a></section>+<section class="view" id="page-2"><h1>Report: page 2</h1>+<a href="#page-1">Previous</a></section>+<section class="view" id="detail"><h1>Report: details</h1>+<a href="#detail">Details again</a><a href="#page-1">Return to home</a></section>+<output id="hash-events" hidden>0</output>+<script>+window.addEventListener('hashchange', function() {+ var output = document.getElementById('hash-events');+ output.textContent = String(Number(output.textContent) + 1);+});+window.addEventListener('keydown', function(e) {+ if (e.key === 'ArrowRight') location.hash = '#page-2';+});+window.addEventListener('click', function(e) {+ document.documentElement.dataset.clickPrevented = String(e.defaultPrevented);+});+</script></body></html>`;++const longReport = `<!doctype html><html><body>+ <nav style="position:fixed;top:0;background:white">+ <a href="#section">Section</a>+ <a href="#%E4%B8%AD%E6%96%87">Encoded</a>+ <a href="#legacy">Legacy</a>+ <a href="#section" onclick="event.preventDefault()">Author handled</a>+ <a href="#/route">Hash router</a>+ </nav>+ <div style="height:2000px"></div><h1 id="section">Section</h1>+ <div style="height:2000px"></div><h1 id="中文">Encoded section</h1>+ <div style="height:2000px"></div><a name="legacy">Legacy section</a>+ <div style="height:1000px"></div>+</body></html>`;++function requireLocal(baseURL: string) {+ const local = (url: string) =>+ ["localhost", "127.0.0.1", "[::1]"].includes(new URL(url).hostname);+ test.skip(!local(baseURL) || !local(apiBase), "Isolated local fixtures only");+}++async function openPreview(page: Page, api: TestApiClient, surface: "standalone" | "modal", html = report) {+ const slug = await loginAsDefault(page);+ const previousUrl = page.url();+ const issue = await api.createIssue("HTML fragment navigation regression");+ const form = new FormData();+ form.append("file", new Blob([html], { type: "text/html" }), "fragment-report.html");+ form.append("issue_id", issue.id);+ const uploaded = await fetch(`${apiBase}/api/upload-file`, {+ method: "POST",+ headers: { Authorization: `Bearer ${api.getToken()}`, "X-Workspace-Slug": slug },+ body: form,+ });+ expect(uploaded.status).toBe(200);+ const attachment = await uploaded.json();+ if (surface === "standalone") {+ await page.goto(`/${slug}/attachments/${attachment.id}/preview`);+ } else {+ await api.updateIssue(issue.id, {+ description: `!file[fragment-report.html](${attachment.markdown_url})`,+ });+ await page.goto(`/${slug}/issues/${issue.identifier}`);+ await page.getByRole("button", { name: "Preview", exact: true }).first().click();+ await expect(page.getByRole("dialog")).toBeVisible();+ }+ const iframe = page.locator('iframe[title="fragment-report.html"]');+ await expect(iframe).toBeVisible();+ return { iframe, previousUrl };+}++for (const surface of ["standalone", "modal"] as const) {+ test(`HTML fragment links preserve pagination without growing history in ${surface}`, async ({ page, baseURL }, testInfo) => {+ test.setTimeout(120000);+ requireLocal(baseURL!);+ await page.setViewportSize({ width: 1440, height: 900 });+ const api = await createTestApi();+ try {+ const { iframe } = await openPreview(page, api, surface);+ await expect(iframe).toHaveAttribute("sandbox", "allow-scripts");+ const frame = iframe.contentFrame();+ await expect(frame.getByRole("heading", { name: "Report: page 1" })).toBeVisible();+ const documentFrame = (await (await iframe.elementHandle())!.contentFrame())!;+ const timeOrigin = await documentFrame.evaluate(() => performance.timeOrigin);+ const historyLength = await page.evaluate(() => history.length);++ await frame.getByRole("link", { name: "Next", exact: true }).click();+ await testInfo.attach("after-next-state", {+ body: Buffer.from(JSON.stringify(await documentFrame.evaluate(() => ({+ hash: location.hash,+ target: document.querySelector(":target")?.id ?? null,+ visible: [...document.querySelectorAll(".view")]+ .filter((el) => getComputedStyle(el).display !== "none").map((el) => el.id),+ defaultPrevented: document.documentElement.dataset.clickPrevented,+ })))),+ contentType: "application/json",+ });+ const afterNext = testInfo.outputPath("after-next.png");+ await page.screenshot({ path: afterNext });+ await testInfo.attach("after-next", { path: afterNext, contentType: "image/png" });+ await expect(frame.getByRole("heading", { name: "Report: page 2" })).toBeVisible();+ await expect(page.getByRole("textbox", { name: "Address", exact: true })).toHaveValue("#page-2");+ await expect(frame.locator("#hash-events")).toHaveText("1");+ expect(await page.evaluate(() => history.length)).toBe(historyLength);++ await frame.getByRole("link", { name: "Previous", exact: true }).click();+ await expect(frame.getByRole("heading", { name: "Report: page 1" })).toBeVisible();+ await frame.getByRole("link", { name: "Details", exact: true }).click();+ await expect(frame.getByRole("heading", { name: "Report: details" })).toBeVisible();+ await expect(frame.locator("#hash-events")).toHaveText("3");+ await expect(page.getByRole("textbox", { name: "Address", exact: true })).toHaveValue("#detail");+ expect(await page.evaluate(() => history.length)).toBe(historyLength);+ await frame.getByRole("link", { name: "Details again", exact: true }).click();+ expect(await documentFrame.evaluate(() => history.length)).toBe(historyLength);+ await expect(frame.locator("#hash-events")).toHaveText("3");++ const details = testInfo.outputPath("details.png");+ await page.screenshot({ path: details });+ await testInfo.attach("details", { path: details, contentType: "image/png" });+ await frame.getByRole("link", { name: "Return to home", exact: true }).click();+ await expect(frame.getByRole("heading", { name: "Report: page 1" })).toBeVisible();+ expect(await page.evaluate(() => history.length)).toBe(historyLength);+ expect(await documentFrame.evaluate(() => performance.timeOrigin)).toBe(timeOrigin);++ // Restoring navigation must not grant uploaded HTML access to its host.+ expect(await documentFrame.evaluate(() => {+ const blocked = (read: () => unknown) => { try { read(); return false; } catch { return true; } };+ return {+ parent: blocked(() => parent.document),+ cookies: blocked(() => document.cookie),+ storage: blocked(() => localStorage.length),+ };+ })).toEqual({ parent: true, cookies: true, storage: true });+ } finally {+ await api.cleanup();+ }+ });+}++for (const [kind, html, links] of [+ ["pagination", report, ["Next", "Previous", "Details", "Return to home"]],+ ["ordinary anchors", longReport, ["Section", "Encoded", "Legacy"]],+] as const) {+ test(`closing ${kind} preview leaves with one browser Back`, async ({ page, baseURL }, testInfo) => {+ test.setTimeout(120000);+ requireLocal(baseURL!);+ const api = await createTestApi();+ try {+ const { iframe, previousUrl } = await openPreview(page, api, "modal", html);+ const historyBefore = await page.evaluate(() => history.length);+ for (const name of links) {+ await iframe.contentFrame().getByRole("link", { name, exact: true }).click();+ }+ const historyBeforeClose = await page.evaluate(() => history.length);+ await page.getByRole("dialog").getByRole("button", { name: "Close", exact: true }).click();+ await expect(page.getByRole("dialog")).toBeHidden();+ await page.goBack({ waitUntil: "domcontentloaded" });+ await testInfo.attach("one-back-state", {+ body: Buffer.from(JSON.stringify({ kind, historyBefore, historyBeforeClose, previousUrl, afterOneBack: page.url() })),+ contentType: "application/json",+ });+ await expect(page).toHaveURL(previousUrl);+ await expect(page.getByRole("button", { name: "New Issue", exact: true }).first()).toBeVisible();+ await expect(page.getByText("HTML fragment navigation regression", { exact: true })).toBeVisible();+ const screenshot = testInfo.outputPath("after-one-back.png");+ await page.screenshot({ path: screenshot });+ await testInfo.attach("after-one-back", { path: screenshot, contentType: "image/png" });+ expect(historyBeforeClose).toBe(historyBefore);+ } finally {+ await api.cleanup();+ }+ });+}++test("report-authored hash writes keep their own history behavior", async ({ page, baseURL, browserName }) => {+ test.setTimeout(120000);+ test.skip(browserName !== "chromium", "Chromium retains removed iframe history");+ requireLocal(baseURL!);+ const api = await createTestApi();+ try {+ const { iframe, previousUrl } = await openPreview(page, api, "modal");+ const issueUrl = page.url();+ const historyBefore = await page.evaluate(() => history.length);+ await iframe.contentFrame().getByRole("heading", { name: "Report: page 1" }).click();+ // The report's own key handler assigns location.hash, outside the shim.+ await page.keyboard.press("ArrowRight");+ await expect(iframe.contentFrame().getByRole("heading", { name: "Report: page 2" })).toBeVisible();+ await expect(page.getByRole("textbox", { name: "Address", exact: true })).toHaveValue("#page-2");+ expect(await page.evaluate(() => history.length)).toBe(historyBefore + 1);+ await iframe.contentFrame().getByRole("link", { name: "Previous", exact: true }).click();+ await page.getByRole("dialog").getByRole("button", { name: "Close", exact: true }).click();+ await expect(page.getByRole("dialog")).toBeHidden();+ await page.goBack({ waitUntil: "domcontentloaded" });+ await expect(page).toHaveURL(issueUrl);+ await page.goBack({ waitUntil: "domcontentloaded" });+ await expect(page).toHaveURL(previousUrl);+ } finally {+ await api.cleanup();+ }+});++// Browser-level coverage for the shipped shim and bridge; no product fixtures.+test("fragment shim keeps long-document anchors and author handlers working", async ({ page }) => {+ const html = withLocationBridge(withFragmentNavShim(longReport), "");+ await page.setContent('<iframe sandbox="allow-scripts" title="Long document" style="width:800px;height:400px"></iframe>');+ await page.locator("iframe").evaluate((element, source) => { element.setAttribute("srcdoc", source); }, html);+ const frame = page.frameLocator("iframe");+ const documentFrame = (await (await page.locator("iframe").elementHandle())!.contentFrame())!;+ for (const [label, hash, selector] of [+ ["Section", "#section", "#section"],+ ["Encoded", "#%E4%B8%AD%E6%96%87", "#中文"],+ ["Legacy", "#legacy", 'a[name="legacy"]'],+ ]) {+ await frame.getByRole("link", { name: label, exact: true }).click();+ await expect.poll(() => documentFrame.evaluate(() => location.hash)).toBe(hash);+ await expect.poll(() => frame.locator(selector).evaluate((el) => Math.abs(el.getBoundingClientRect().top))).toBeLessThan(2);+ }+ await frame.getByRole("link", { name: "Author handled", exact: true }).click();+ expect(await documentFrame.evaluate(() => location.hash)).toBe("#legacy");+ await frame.getByRole("link", { name: "Hash router", exact: true }).click();+ await expect.poll(() => documentFrame.evaluate(() => location.hash)).toBe("#/route");+});diff --git a/packages/views/editor/utils/iframe-fragment-nav.test.ts b/packages/views/editor/utils/iframe-fragment-nav.test.tsindex 43e6dbd440..09fe4476b3 100644--- a/packages/views/editor/utils/iframe-fragment-nav.test.ts+++ b/packages/views/editor/utils/iframe-fragment-nav.test.ts@@ -1,5 +1,6 @@import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";import { __FRAGMENT_NAV_SHIM__ } from "./iframe-fragment-nav";+import { __locationBridgeScript__, HTML_PREVIEW_LOCATION_KEY } from "./iframe-location-bridge";// The shim itself ships as a <script> string injected into a srcdoc iframe.// To exercise its runtime behavior in unit tests, evaluate the inner script@@ -8,17 +9,31 @@ import { __FRAGMENT_NAV_SHIM__ } from "./iframe-fragment-nav";//// scrollIntoView is not implemented in jsdom; we stub it per-test.function loadShimIntoDocument() {+ const registration = vi.spyOn(document, "addEventListener");const inner = __FRAGMENT_NAV_SHIM__.replace(/^<script>/, "").replace(/<\/script>$/, "");new Function(inner)();+ const listeners = [...registration.mock.calls];+ registration.mockRestore();+ return () => {+ for (const [type, listener, options] of listeners) {+ document.removeEventListener(type, listener, options);+ }+ };}describe("fragment-nav shim runtime behavior", () => {let scrollSpy: ReturnType<typeof vi.fn>;+ let hashChange: ReturnType<typeof vi.fn<(event: HashChangeEvent) => void>>;+ let unloadShim: () => void;+ let unloadBridge: (() => void) | undefined;beforeEach(() => {document.body.innerHTML = "";+ window.history.replaceState(null, "", "/report?s=overview");+ hashChange = vi.fn<(event: HashChangeEvent) => void>();+ window.addEventListener("hashchange", hashChange);scrollSpy = vi.fn();// Patch the prototype so any element we create inherits the stub.Object.defineProperty(window.Element.prototype, "scrollIntoView", {@@ -26,17 +41,61 @@ describe("fragment-nav shim runtime behavior", () => {writable: true,value: scrollSpy,});- loadShimIntoDocument();+ unloadShim = loadShimIntoDocument();});- afterEach(() => {+ afterEach(async () => {+ unloadShim();+ unloadBridge?.();+ unloadBridge = undefined;+ window.removeEventListener("hashchange", hashChange);document.body.innerHTML = "";- // Reload document listeners by clearing the DOM; jsdom isolates the- // listener registration to the document instance, but next test calls- // loadShimIntoDocument() again — that double-registers handlers across- // tests within the same document. We isolate by recreating the link- // each test and asserting based on whether scrollIntoView fired *on the- // intended target*, not call-count totals.+ vi.restoreAllMocks();+ // Drain native hashchange tasks before the next test installs listeners.+ await new Promise((resolve) => setTimeout(resolve, 0));+ });++ it.each([false, true])("updates fragments without adding history (location bridge: %s)", async (withBridge) => {+ const postMessage = vi.spyOn(window, "postMessage").mockImplementation(() => {});+ if (withBridge) {+ const registration = vi.spyOn(window, "addEventListener");+ new Function(__locationBridgeScript__(""))();+ const listeners = [...registration.mock.calls];+ registration.mockRestore();+ unloadBridge = () => {+ for (const [type, listener, options] of listeners) {+ window.removeEventListener(type, listener, options);+ }+ delete (window.history as Partial<History>).pushState;+ delete (window.history as Partial<History>).replaceState;+ };+ }+ document.body.innerHTML = '<section id="page-2"></section><section id="detail"></section><a>Go</a>';+ const link = document.querySelector("a")!;+ const historyLength = window.history.length;+ let oldURL = window.location.href;+ for (const [index, hash] of ["#page-2", "#detail"].entries()) {+ link.setAttribute("href", hash);+ link.click();+ await vi.waitFor(() => expect(hashChange).toHaveBeenCalledTimes(index + 1));+ expect(window.location.search + window.location.hash).toBe(`?s=overview${hash}`);+ expect(document.querySelector(":target")?.id).toBe(hash.slice(1));+ expect(window.history.length).toBe(historyLength);+ const event = hashChange.mock.calls[index]![0];+ expect(event.oldURL).toBe(oldURL);+ expect(event.newURL).toBe(window.location.href);+ oldURL = window.location.href;+ if (withBridge) {+ expect(postMessage).toHaveBeenCalledWith({+ [HTML_PREVIEW_LOCATION_KEY]: 1, type: "location", value: `?s=overview${hash}`,+ }, "*");+ }+ }+ // Repeating the active fragment must neither add history nor fire again.+ link.click();+ await new Promise((resolve) => setTimeout(resolve, 0));+ expect(hashChange).toHaveBeenCalledTimes(2);+ expect(window.history.length).toBe(historyLength);});it("scrolls the matching target into view when a fragment link is clicked", () => {diff --git a/packages/views/editor/utils/iframe-fragment-nav.ts b/packages/views/editor/utils/iframe-fragment-nav.tsindex e9aca5dede..f66219a46f 100644--- a/packages/views/editor/utils/iframe-fragment-nav.ts+++ b/packages/views/editor/utils/iframe-fragment-nav.ts@@ -13,11 +13,14 @@* implementation consensus, not a bug we can wait out.** The fix is in-iframe: append a tiny script to the document that listens for- * fragment-link clicks and calls `scrollIntoView` itself. The script runs in- * the iframe's own opaque origin — same capabilities the user's HTML already- * has under `allow-scripts`; it cannot reach the parent. The shim only- * intercepts `href="#..."` clicks, defers to any preventDefault handler the- * user's HTML installed, and stays out of the way when the target id is+ * fragment-link clicks, replaces the document's own fragment, and scrolls.+ * This activates :target and fires hashchange before scrolling, without adding+ * session history entries. Chromium retains iframe history after unmount, so+ * adding entries would leave invisible Back steps when a preview closes.+ * The script runs in the iframe's own opaque origin — same capabilities the+ * user's HTML already has under `allow-scripts`; it cannot reach the parent.+ * The shim only intercepts `href="#..."` clicks, defers to any preventDefault+ * handler the user's HTML installed, and stays out of the way when the target id is* missing (so SPA / tab-style routers in the document can still handle it).*/const FRAGMENT_NAV_SHIM = `<script>@@ -39,6 +42,7 @@ const FRAGMENT_NAV_SHIM = `<script>}if (!dest) return;e.preventDefault();+ window.location.replace(window.location.href.split('#')[0] + href);dest.scrollIntoView({ behavior: 'smooth', block: 'start' });});})();