Shared task board where people and AI coding agents work as teammates. Source-available, self-hostable.
Go
fix(editor): make in-iframe #fragment links scroll in HTML attachment preview (MUL-2417) (#2855)
Naiyuan Qingc49c78b78070
diff --git a/packages/views/attachments/attachment-preview-page.tsx b/packages/views/attachments/attachment-preview-page.tsxindex 329c5c4523..1135bba75f 100644--- a/packages/views/attachments/attachment-preview-page.tsx+++ b/packages/views/attachments/attachment-preview-page.tsx@@ -21,6 +21,7 @@import { useEffect } from "react";import { useT } from "../i18n";import { useAttachmentHtmlText } from "../editor/hooks/use-attachment-html-text";+import { withFragmentNavShim } from "../editor/utils/iframe-fragment-nav";interface AttachmentPreviewPageProps {attachmentId: string;@@ -61,7 +62,7 @@ export function AttachmentPreviewPage({</div>) : (<iframe- srcDoc={text}+ srcDoc={withFragmentNavShim(text)}sandbox="allow-scripts"title={filename ?? "HTML attachment"}className="flex-1 w-full border-0 bg-background"diff --git a/packages/views/editor/attachment-preview-modal.test.tsx b/packages/views/editor/attachment-preview-modal.test.tsxindex a49774efc4..37b3bf8d35 100644--- a/packages/views/editor/attachment-preview-modal.test.tsx+++ b/packages/views/editor/attachment-preview-modal.test.tsx@@ -230,7 +230,11 @@ 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");- expect(frame?.getAttribute("srcdoc")).toBe("<p>hi</p>");+ // srcdoc carries the original HTML plus the fragment-nav shim+ // appended at the end (see utils/iframe-fragment-nav.ts).+ const srcdoc = frame?.getAttribute("srcdoc") ?? "";+ expect(srcdoc.startsWith("<p>hi</p>")).toBe(true);+ expect(srcdoc).toContain("scrollIntoView");});});diff --git a/packages/views/editor/attachment-preview-modal.tsx b/packages/views/editor/attachment-preview-modal.tsxindex 39e94a2555..ed9bb863d0 100644--- a/packages/views/editor/attachment-preview-modal.tsx+++ b/packages/views/editor/attachment-preview-modal.tsx@@ -56,6 +56,7 @@ import {} from "./utils/preview";import { useDownloadAttachment } from "./use-download-attachment";import { useAttachmentHtmlText } from "./hooks/use-attachment-html-text";+import { withFragmentNavShim } from "./utils/iframe-fragment-nav";import { CodeBlockStatic } from "./code-block-static";// ---------------------------------------------------------------------------@@ -399,7 +400,7 @@ function PreviewContent({onDownload={onDownload}render={(text) => (<iframe- srcDoc={text}+ srcDoc={withFragmentNavShim(text)}// `allow-scripts` without `allow-same-origin` — scripts run// in an opaque origin and cannot read cookies / localStorage// / parent state, nor escape via top-nav / popups / forms.diff --git a/packages/views/editor/html-attachment-preview.test.tsx b/packages/views/editor/html-attachment-preview.test.tsxindex ebe18578d1..c371c8d3e4 100644--- a/packages/views/editor/html-attachment-preview.test.tsx+++ b/packages/views/editor/html-attachment-preview.test.tsx@@ -117,7 +117,11 @@ describe("HtmlAttachmentPreview — visual shell (does not use file-card chrome)// Critical: sandbox must not include allow-same-origin, otherwise the// sandbox is defeated per the HTML spec.expect(frame?.getAttribute("sandbox")).toBe("allow-scripts");- expect(frame?.getAttribute("srcdoc")).toBe("<p>chart goes here</p>");+ // srcdoc carries the original HTML plus the fragment-nav shim+ // appended at the end (see utils/iframe-fragment-nav.ts).+ const srcdoc = frame?.getAttribute("srcdoc") ?? "";+ expect(srcdoc.startsWith("<p>chart goes here</p>")).toBe(true);+ expect(srcdoc).toContain("scrollIntoView");});});});diff --git a/packages/views/editor/html-attachment-preview.tsx b/packages/views/editor/html-attachment-preview.tsxindex 449f4c34ad..49d5396271 100644--- a/packages/views/editor/html-attachment-preview.tsx+++ b/packages/views/editor/html-attachment-preview.tsx@@ -32,6 +32,7 @@ import { paths, useWorkspaceSlug } from "@multica/core/paths";import { useT } from "../i18n";import { useNavigation } from "../navigation";import { useAttachmentHtmlText } from "./hooks/use-attachment-html-text";+import { withFragmentNavShim } from "./utils/iframe-fragment-nav";const PREVIEW_HEIGHT = "h-[480px]";const ERROR_PLACEHOLDER_HEIGHT = "h-20";@@ -105,7 +106,7 @@ export function HtmlAttachmentPreview({</div>) : (<iframe- srcDoc={text}+ srcDoc={withFragmentNavShim(text)}sandbox="allow-scripts"title={filename}className={cn(diff --git a/packages/views/editor/utils/iframe-fragment-nav.test.ts b/packages/views/editor/utils/iframe-fragment-nav.test.tsnew file mode 100644index 0000000000..2fc25dfbc3--- /dev/null+++ b/packages/views/editor/utils/iframe-fragment-nav.test.ts@@ -0,0 +1,187 @@+import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";+import {+ __FRAGMENT_NAV_SHIM__,+ withFragmentNavShim,+} from "./iframe-fragment-nav";++describe("withFragmentNavShim", () => {+ it("appends the shim verbatim at the end of the original HTML", () => {+ const html = "<h1 id='a'>A</h1><a href='#a'>jump</a>";+ const out = withFragmentNavShim(html);+ expect(out.startsWith(html)).toBe(true);+ expect(out.endsWith(__FRAGMENT_NAV_SHIM__)).toBe(true);+ expect(out).toBe(html + __FRAGMENT_NAV_SHIM__);+ });++ it("does not mutate the input string", () => {+ const html = "<p>hi</p>";+ withFragmentNavShim(html);+ expect(html).toBe("<p>hi</p>");+ });++ it("handles empty input", () => {+ expect(withFragmentNavShim("")).toBe(__FRAGMENT_NAV_SHIM__);+ });+});++// 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+// against the current document — jsdom's environment matches what runs inside+// the iframe closely enough for the click-handling contract.+//+// scrollIntoView is not implemented in jsdom; we stub it per-test.+function loadShimIntoDocument() {+ const inner = __FRAGMENT_NAV_SHIM__+ .replace(/^<script>/, "")+ .replace(/<\/script>$/, "");+ new Function(inner)();+}++describe("fragment-nav shim runtime behavior", () => {+ let scrollSpy: ReturnType<typeof vi.fn>;++ beforeEach(() => {+ document.body.innerHTML = "";+ scrollSpy = vi.fn();+ // Patch the prototype so any element we create inherits the stub.+ Object.defineProperty(window.Element.prototype, "scrollIntoView", {+ configurable: true,+ writable: true,+ value: scrollSpy,+ });+ loadShimIntoDocument();+ });++ afterEach(() => {+ 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.+ });++ it("scrolls the matching target into view when a fragment link is clicked", () => {+ const section = document.createElement("section");+ section.id = "intro";+ section.textContent = "intro";+ document.body.appendChild(section);++ const link = document.createElement("a");+ link.setAttribute("href", "#intro");+ link.textContent = "go";+ document.body.appendChild(link);++ const evt = new MouseEvent("click", { bubbles: true, cancelable: true });+ link.dispatchEvent(evt);++ expect(scrollSpy).toHaveBeenCalled();+ expect(scrollSpy.mock.instances[0]).toBe(section);+ expect(evt.defaultPrevented).toBe(true);+ });++ it("falls back to <a name='...'> when no element id matches", () => {+ const target = document.createElement("a");+ target.setAttribute("name", "legacy");+ document.body.appendChild(target);++ const link = document.createElement("a");+ link.setAttribute("href", "#legacy");+ document.body.appendChild(link);++ const evt = new MouseEvent("click", { bubbles: true, cancelable: true });+ link.dispatchEvent(evt);++ expect(scrollSpy).toHaveBeenCalled();+ expect(scrollSpy.mock.instances[0]).toBe(target);+ expect(evt.defaultPrevented).toBe(true);+ });++ it("decodes percent-encoded fragment ids", () => {+ const section = document.createElement("section");+ section.id = "中文";+ document.body.appendChild(section);++ const link = document.createElement("a");+ link.setAttribute("href", `#${encodeURIComponent("中文")}`);+ document.body.appendChild(link);++ link.dispatchEvent(new MouseEvent("click", { bubbles: true, cancelable: true }));++ expect(scrollSpy).toHaveBeenCalled();+ expect(scrollSpy.mock.instances[0]).toBe(section);+ });++ it("does not intercept when the click target is not inside an anchor", () => {+ const div = document.createElement("div");+ div.textContent = "not a link";+ document.body.appendChild(div);++ const evt = new MouseEvent("click", { bubbles: true, cancelable: true });+ div.dispatchEvent(evt);++ expect(scrollSpy).not.toHaveBeenCalled();+ expect(evt.defaultPrevented).toBe(false);+ });++ it("does not intercept links to external URLs", () => {+ const link = document.createElement("a");+ link.setAttribute("href", "https://example.com/page#section");+ document.body.appendChild(link);++ const evt = new MouseEvent("click", { bubbles: true, cancelable: true });+ link.dispatchEvent(evt);++ expect(scrollSpy).not.toHaveBeenCalled();+ expect(evt.defaultPrevented).toBe(false);+ });++ it("does not intercept bare '#' links", () => {+ const link = document.createElement("a");+ link.setAttribute("href", "#");+ document.body.appendChild(link);++ const evt = new MouseEvent("click", { bubbles: true, cancelable: true });+ link.dispatchEvent(evt);++ expect(scrollSpy).not.toHaveBeenCalled();+ expect(evt.defaultPrevented).toBe(false);+ });++ it("does not intercept when target id is missing — lets in-document handlers run", () => {+ const link = document.createElement("a");+ link.setAttribute("href", "#nonexistent");+ document.body.appendChild(link);++ const evt = new MouseEvent("click", { bubbles: true, cancelable: true });+ link.dispatchEvent(evt);++ expect(scrollSpy).not.toHaveBeenCalled();+ expect(evt.defaultPrevented).toBe(false);+ });++ it("yields to a user handler that already called preventDefault", () => {+ const section = document.createElement("section");+ section.id = "intro";+ document.body.appendChild(section);++ const link = document.createElement("a");+ link.setAttribute("href", "#intro");+ document.body.appendChild(link);++ // A user-installed handler that suppresses default behavior. Capture+ // phase + preventDefault — our shim must see defaultPrevented and bail.+ document.addEventListener(+ "click",+ (e) => {+ if (e.target === link) e.preventDefault();+ },+ true,+ );++ link.dispatchEvent(new MouseEvent("click", { bubbles: true, cancelable: true }));++ expect(scrollSpy).not.toHaveBeenCalled();+ });+});diff --git a/packages/views/editor/utils/iframe-fragment-nav.ts b/packages/views/editor/utils/iframe-fragment-nav.tsnew file mode 100644index 0000000000..e9aca5dede--- /dev/null+++ b/packages/views/editor/utils/iframe-fragment-nav.ts@@ -0,0 +1,52 @@+/**+ * Fragment-navigation shim for sandboxed HTML attachment iframes.+ *+ * HTML attachment previews mount the user-supplied document inside a+ * `<iframe sandbox="allow-scripts" srcdoc={...}>` — deliberately WITHOUT+ * `allow-same-origin`, because the source is untrusted user upload and+ * same-origin would let it reach cookies / localStorage / parent.document.+ *+ * That security posture has a side effect: in Chromium, a sandboxed srcdoc+ * iframe sits in an opaque origin, and the browser treats clicks on+ * `<a href="#section">` as cross-origin frame navigation — silently rejected,+ * no scroll, no error. See whatwg/html#3537 and crbug 40191760; it's a spec ++ * 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+ * missing (so SPA / tab-style routers in the document can still handle it).+ */+const FRAGMENT_NAV_SHIM = `<script>+(function(){+ document.addEventListener('click', function(e) {+ if (e.defaultPrevented) return;+ var t = e.target;+ if (!t || typeof t.closest !== 'function') return;+ var a = t.closest('a[href]');+ if (!a) return;+ var href = a.getAttribute('href');+ if (!href || href.charAt(0) !== '#' || href === '#') return;+ var id;+ try { id = decodeURIComponent(href.slice(1)); } catch (_) { return; }+ if (!id) return;+ var dest = document.getElementById(id);+ if (!dest && typeof CSS !== 'undefined' && CSS.escape) {+ dest = document.querySelector('a[name="' + CSS.escape(id) + '"]');+ }+ if (!dest) return;+ e.preventDefault();+ dest.scrollIntoView({ behavior: 'smooth', block: 'start' });+ });+})();+</script>`;++export function withFragmentNavShim(html: string | undefined): string {+ return (html ?? "") + FRAGMENT_NAV_SHIM;+}++/** Exposed for unit tests so they can assert the shim was appended verbatim. */+export const __FRAGMENT_NAV_SHIM__ = FRAGMENT_NAV_SHIM;