From ad3c490a528eef6d076ca763033a6e887ddba31d Mon Sep 17 00:00:00 2001 From: "paseo-bot[bot]" <266920839+paseo-bot[bot]@users.noreply.github.com> Date: Thu, 19 Nov 2026 09:53:05 +0000 Subject: [PATCH] Keep a file view's scroll position when switching Preview and Source (#10195) * Keep a file view's scroll offset when switching Preview and Source A file tab rendered either its Preview or its Source, so each switch unmounted the view on screen and its scroll offset with it. Coming back started at the top of the file. Each view now stays mounted once shown and is hidden with RetainedPanel while the other view shows. The hidden Preview keeps the text it last showed, so editing in Source does not render it on every change. Co-authored-by: apple-ouyang <45086632+apple-ouyang@users.noreply.github.com> Co-Authored-By: Claude Opus 5.5 * Assert what the file pane shows, not that the other view unmounted The Preview and Source views now stay mounted once shown, so the file editing spec checks the visible heading and a hidden HTML preview. Co-Authored-By: Claude Opus 5.5 * Load the HTML preview again in the WebView that shows after a hidden panel iOS destroys the native WebView of a hidden retained panel and makes a new one when the panel shows. The navigation guard latched the document per component mount, so it refused the new WebView's load of the same document and the preview stayed blank after Source -> Preview. The guard now releases the latch while its retained panel is hidden. Co-Authored-By: Claude Opus 5.5 * Name the iOS HTML preview as the view that does not keep its offset Co-Authored-By: Claude Opus 5.5 * Load a changed HTML document in a new preview frame on web The Preview stays mounted and hidden while Source shows. When the file changed meanwhile, the Preview got the new document in the same render that showed it again. Chromium left the reused iframe blank in that case until the next Source/Preview switch. Key the iframe by its document so each document loads in a new frame. Co-Authored-By: Claude Opus 5.5 --------- Co-authored-by: paseo-bot[bot] <266920839+paseo-bot[bot]@users.noreply.github.com> Co-authored-by: apple-ouyang <45086632+apple-ouyang@users.noreply.github.com> Co-authored-by: Claude Opus 5.5 --- packages/app/e2e/browser/file-editing.spec.ts | 47 ++++++- .../app/e2e/browser/file-view-scroll.spec.ts | 130 ++++++++++++++++++ .../html-preview-navigation-guard.test.tsx | 48 +++++++ .../file-panels/html-preview-navigation.ts | 35 +++++ packages/app/src/file-panels/html-preview.tsx | 20 +-- .../src/file-panels/html-preview.web.test.tsx | 18 +++ .../app/src/file-panels/html-preview.web.tsx | 4 + packages/app/src/file-panels/source/panel.tsx | 76 ++++++++-- 8 files changed, 350 insertions(+), 28 deletions(-) create mode 100644 packages/app/e2e/browser/file-view-scroll.spec.ts create mode 100644 packages/app/src/file-panels/html-preview-navigation-guard.test.tsx create mode 100644 packages/app/src/file-panels/html-preview.web.test.tsx diff --git a/packages/app/e2e/browser/file-editing.spec.ts b/packages/app/e2e/browser/file-editing.spec.ts index 049c765640..caac7d040c 100644 --- a/packages/app/e2e/browser/file-editing.spec.ts +++ b/packages/app/e2e/browser/file-editing.spec.ts @@ -777,7 +777,9 @@ test.describe("CodeMirror workspace file editing", () => { await replaceEditorText(page, "# Saved from source\n"); await expect(page.getByTestId("workspace-tab-modified-file_notes.md")).toBeVisible(); await selectFileView(page, "Preview"); - await expect(visibleFilePane.getByText("Saved from source", { exact: true })).toBeVisible(); + await expect( + visibleFilePane.getByRole("heading", { name: "Saved from source", exact: true }), + ).toBeVisible(); await expect(toolbar.getByLabel("Line 1, column 1")).toHaveCount(0); await expect.poll(() => readFile(markdownPath, "utf8")).toBe("# Saved from source\n"); await expect(page.getByTestId("workspace-tab-modified-file_notes.md")).not.toBeVisible(); @@ -864,11 +866,52 @@ test.describe("CodeMirror workspace file editing", () => { await selectFileView(page, "Source"); await expect(page.getByTestId("file-source-editor")).toBeVisible(); - await expect(preview.host).toHaveCount(0); + await expect(preview.host).toBeHidden(); await selectFileView(page, "Preview"); await expect(preview.host).toBeVisible(); }); + test("shows the changed HTML page after the file changes on disk while Source shows", async ({ + page, + withWorkspace, + }) => { + const workspace = await withWorkspace({ prefix: "file-editing-html-hidden-change-" }); + const htmlPath = path.join(workspace.repoPath, "plan.html"); + await writeFile(htmlPath, "

First plan

"); + await workspace.navigateTo(); + await openWorkspaceFile(page, "plan.html"); + const preview = htmlPreview(page); + await expect(preview.document.getByRole("heading", { name: "First plan" })).toBeVisible(); + + await selectFileView(page, "Source"); + await writeFile(htmlPath, "

Changed on disk

"); + await expect(editor(page)).toContainText("Changed on disk"); + await selectFileView(page, "Preview"); + + await expect(preview.document.getByRole("heading", { name: "Changed on disk" })).toBeVisible(); + }); + + test("shows the HTML page edited in Source when Preview shows again", async ({ + page, + withWorkspace, + }) => { + const workspace = await withWorkspace({ prefix: "file-editing-html-hidden-edit-" }); + await writeFile( + path.join(workspace.repoPath, "plan.html"), + "

First plan

", + ); + await workspace.navigateTo(); + await openWorkspaceFile(page, "plan.html"); + const preview = htmlPreview(page); + await expect(preview.document.getByRole("heading", { name: "First plan" })).toBeVisible(); + + await selectFileView(page, "Source"); + await replaceEditorText(page, "

Edited plan

"); + await selectFileView(page, "Preview"); + + await expect(preview.document.getByRole("heading", { name: "Edited plan" })).toBeVisible(); + }); + test("keeps HTML fragment links in the preview and scrolls to the target", async ({ page, withWorkspace, diff --git a/packages/app/e2e/browser/file-view-scroll.spec.ts b/packages/app/e2e/browser/file-view-scroll.spec.ts new file mode 100644 index 0000000000..9aac09d32d --- /dev/null +++ b/packages/app/e2e/browser/file-view-scroll.spec.ts @@ -0,0 +1,130 @@ +import { writeFile } from "node:fs/promises"; +import path from "node:path"; +import { expect, test, type Page } from "../support/fixtures"; +import { openFileExplorer, openFileFromExplorer } from "../support/helpers/file-explorer"; + +// Switching a file tab between Preview and Source returns to where each view was left. + +const sections = Array.from({ length: 200 }, (_, index) => index); +const LONG_MARKDOWN = sections.map((i) => `## Section ${i}\n\nParagraph ${i}.\n`).join("\n"); +const LONG_HTML = `${sections + .map((i) => `

Section ${i}

Paragraph ${i}

`) + .join("")}`; + +type FileView = "markdown preview" | "html preview" | "source"; + +function htmlPreviewFrame(page: Page) { + const frame = page.frames().find((candidate) => candidate.url().startsWith("data:text/html")); + if (!frame) throw new Error("The HTML preview frame is not loaded."); + return frame; +} + +/** + * Moves the view's visible scroller to `offset` when given, and returns its offset. The + * scroller is Markdown's scroll view, CodeMirror's scroller, or the HTML page itself. + */ +async function viewScroll(page: Page, view: FileView, offset?: number): Promise { + if (view === "html preview") { + return htmlPreviewFrame(page).evaluate((target) => { + if (target !== undefined) window.scrollTo(0, target); + return window.scrollY; + }, offset); + } + return page.evaluate( + (input) => { + const visible = (element: HTMLElement) => element.offsetParent !== null; + let scroller: HTMLElement | null; + if (input.view === "source") { + scroller = + [...document.querySelectorAll(".cm-scroller")].find(visible) ?? null; + } else { + scroller = + [ + ...document.querySelectorAll('[data-testid="markdown-preview-frame"]'), + ].find(visible) ?? null; + while (scroller && !(scroller.scrollHeight > scroller.clientHeight + 10)) { + scroller = scroller.parentElement; + } + } + if (!scroller) throw new Error(`No visible scroller for the ${input.view}.`); + if (input.offset !== undefined) scroller.scrollTop = input.offset; + return scroller.scrollTop; + }, + { view, offset }, + ); +} + +async function openLongFile( + page: Page, + withWorkspace: (options?: { prefix?: string }) => Promise<{ + repoPath: string; + navigateTo(): Promise; + }>, + name: string, + content: string, +): Promise { + const workspace = await withWorkspace({ prefix: "file-view-scroll-" }); + await writeFile(path.join(workspace.repoPath, name), content); + await workspace.navigateTo(); + await openFileExplorer(page); + await openFileFromExplorer(page, name); + await expect(page.getByTestId("file-mode-preview")).toBeVisible({ timeout: 30_000 }); +} + +async function showView(page: Page, view: "preview" | "source"): Promise { + await page.getByTestId(`file-mode-${view}`).click(); +} + +/** Scrolls the view past the first screen and returns where it settled. */ +async function scrollDown(page: Page, view: FileView): Promise { + await expect(async () => { + expect(await viewScroll(page, view, 1200)).toBeGreaterThan(1000); + }).toPass({ timeout: 15_000 }); + // CodeMirror can adjust the offset once after a scroll; read it after that settles. + await page.waitForTimeout(300); + return viewScroll(page, view); +} + +async function expectOffsetKept(page: Page, view: FileView, offset: number): Promise { + await expect.poll(() => viewScroll(page, view), { timeout: 5_000 }).toBe(offset); +} + +test("Markdown preview keeps its scroll offset after showing Source", async ({ + page, + withWorkspace, +}) => { + await openLongFile(page, withWorkspace, "long.md", LONG_MARKDOWN); + const offset = await scrollDown(page, "markdown preview"); + + await showView(page, "source"); + await expect(page.getByTestId("file-source-editor")).toBeVisible(); + await showView(page, "preview"); + + await expectOffsetKept(page, "markdown preview", offset); +}); + +test("HTML preview keeps its scroll offset after showing Source", async ({ + page, + withWorkspace, +}) => { + await openLongFile(page, withWorkspace, "long.html", LONG_HTML); + const offset = await scrollDown(page, "html preview"); + + await showView(page, "source"); + await expect(page.getByTestId("file-source-editor")).toBeVisible(); + await showView(page, "preview"); + + await expectOffsetKept(page, "html preview", offset); +}); + +test("Source keeps its scroll offset after showing Preview", async ({ page, withWorkspace }) => { + await openLongFile(page, withWorkspace, "long.md", LONG_MARKDOWN); + await showView(page, "source"); + const offset = await scrollDown(page, "source"); + + await showView(page, "preview"); + await expect(page.getByTestId("markdown-preview-frame")).toBeVisible(); + await showView(page, "source"); + + await expectOffsetKept(page, "source", offset); +}); diff --git a/packages/app/src/file-panels/html-preview-navigation-guard.test.tsx b/packages/app/src/file-panels/html-preview-navigation-guard.test.tsx new file mode 100644 index 0000000000..d9e03ad658 --- /dev/null +++ b/packages/app/src/file-panels/html-preview-navigation-guard.test.tsx @@ -0,0 +1,48 @@ +// @vitest-environment jsdom + +import { renderHook } from "@testing-library/react"; +import type { ReactNode } from "react"; +import { describe, expect, it } from "vitest"; +import { RetainedPanelActivity } from "@/components/retained-panel"; +import { useHtmlPreviewNavigationGuard } from "./html-preview-navigation"; + +const DOCUMENT = "report"; + +function renderGuard(initialActive: boolean) { + let active = initialActive; + const view = renderHook(() => useHtmlPreviewNavigationGuard(DOCUMENT), { + wrapper: ({ children }: { children: ReactNode }) => ( + {children} + ), + }); + return { + navigate: (url: string) => view.result.current({ url }), + setActive(next: boolean) { + active = next; + view.rerender(); + }, + }; +} + +describe("useHtmlPreviewNavigationGuard", () => { + it("loads the document once and refuses the page loading it again", () => { + const guard = renderGuard(true); + + expect(guard.navigate("about:blank")).toBe(true); + expect(guard.navigate("about:blank")).toBe(false); + expect(guard.navigate("https://example.com/leak")).toBe(false); + expect(guard.navigate("about:blank#section")).toBe(true); + }); + + it("loads the document again in the WebView that shows after the panel was hidden", () => { + const guard = renderGuard(true); + expect(guard.navigate("about:blank")).toBe(true); + + // iOS destroys the native WebView of a hidden panel and makes a new one when it shows. + guard.setActive(false); + guard.setActive(true); + + expect(guard.navigate("about:blank")).toBe(true); + expect(guard.navigate("about:blank")).toBe(false); + }); +}); diff --git a/packages/app/src/file-panels/html-preview-navigation.ts b/packages/app/src/file-panels/html-preview-navigation.ts index fafd4e5793..151dd1657f 100644 --- a/packages/app/src/file-panels/html-preview-navigation.ts +++ b/packages/app/src/file-panels/html-preview-navigation.ts @@ -1,3 +1,6 @@ +import { useCallback, useEffect, useRef } from "react"; +import { useRetainedPanelActive } from "@/components/retained-panel"; + export type HtmlPreviewNavigationKind = "initialDocument" | "fragment" | "blocked"; const INITIAL_DOCUMENT_URLS = new Set(["about:blank", "about:srcdoc", ""]); @@ -7,3 +10,35 @@ export function htmlPreviewNavigationKind(url: string): HtmlPreviewNavigationKin if (url.startsWith("about:blank#") || url.startsWith("about:srcdoc#")) return "fragment"; return "blocked"; } + +/** + * Decides each navigation the native WebView asks about: the document loads once, a fragment + * moves within it, and anything else is refused. + */ +export function useHtmlPreviewNavigationGuard( + document: string, +): (request: { url: string }) => boolean { + // Latched per document rather than once for the lifetime of the WebView: the + // file pane re-renders with new content on every live-file refresh, and each of + // those is a fresh initial load that has to be allowed through. + const loadedDocumentRef = useRef(null); + // The latch belongs to one native WebView, not to this component. iOS destroys the WebView of a + // hidden retained panel and makes a new one when the panel shows, and that one loads the + // document again. Releasing the latch while hidden lets that load through; a page on a kept + // WebView gains at most a load of an inert initial URL. + const active = useRetainedPanelActive(); + useEffect(() => { + if (!active) loadedDocumentRef.current = null; + }, [active]); + return useCallback( + ({ url }: { url: string }) => { + const navigationKind = htmlPreviewNavigationKind(url); + if (navigationKind === "fragment") return true; + if (navigationKind === "blocked") return false; + if (loadedDocumentRef.current === document) return false; + loadedDocumentRef.current = document; + return true; + }, + [document], + ); +} diff --git a/packages/app/src/file-panels/html-preview.tsx b/packages/app/src/file-panels/html-preview.tsx index 08ded111e7..752a048390 100644 --- a/packages/app/src/file-panels/html-preview.tsx +++ b/packages/app/src/file-panels/html-preview.tsx @@ -1,8 +1,8 @@ -import { useCallback, useMemo, useRef } from "react"; +import { useMemo } from "react"; import { StyleSheet } from "react-native-unistyles"; import { WebView } from "react-native-webview"; import { withPreviewCsp } from "./html-preview-csp"; -import { htmlPreviewNavigationKind } from "./html-preview-navigation"; +import { useHtmlPreviewNavigationGuard } from "./html-preview-navigation"; // A preview is a viewer, not a browser. Only the document Paseo hands the WebView // loads; navigations the page attempts afterwards are refused, so a link, a @@ -35,21 +35,7 @@ const BASE_URL = "about:blank"; export function FileHtmlPreview({ html, testID }: { html: string; testID?: string }) { const document = useMemo(() => withPreviewCsp(html), [html]); const source = useMemo(() => ({ html: document, baseUrl: BASE_URL }), [document]); - // Latched per document rather than once for the lifetime of the WebView: the - // file pane re-renders with new content on every live-file refresh, and each of - // those is a fresh initial load that has to be allowed through. - const loadedDocumentRef = useRef(null); - const allowOnlyInitialDocument = useCallback( - ({ url }: { url: string }) => { - const navigationKind = htmlPreviewNavigationKind(url); - if (navigationKind === "fragment") return true; - if (navigationKind === "blocked") return false; - if (loadedDocumentRef.current === document) return false; - loadedDocumentRef.current = document; - return true; - }, - [document], - ); + const allowOnlyInitialDocument = useHtmlPreviewNavigationGuard(document); return ( { + it("loads a changed document in a new frame", () => { + const view = render(); + const firstFrame = view.getByTestId("preview"); + + view.rerender(); + const changedFrame = view.getByTestId("preview"); + + expect(changedFrame).not.toBe(firstFrame); + expect(decodeURIComponent(changedFrame.getAttribute("src") ?? "")).toContain("Changed plan"); + }); +}); diff --git a/packages/app/src/file-panels/html-preview.web.tsx b/packages/app/src/file-panels/html-preview.web.tsx index eac275bfe8..fc56a4038b 100644 --- a/packages/app/src/file-panels/html-preview.web.tsx +++ b/packages/app/src/file-panels/html-preview.web.tsx @@ -32,7 +32,11 @@ export function FileHtmlPreview({ html, testID }: { html: string; testID?: strin [html], ); return ( + // Each document loads in a new frame. The Source view keeps this preview mounted and hidden, + // and it gets a changed document in the same render that shows it again. Chromium can leave a + // reused frame blank when it navigates at that moment.