Compare commits

...
Author SHA1 Message Date
paseo-bot[bot]andClaude Opus 5.5 b495d33414 Name the iOS HTML preview as the view that does not keep its offset
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-19 06:40:40 +00:00
paseo-bot[bot]andClaude Opus 5.5 dd1c0424f4 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 <noreply@anthropic.com>
2026-11-19 06:13:22 +00:00
paseo-bot[bot]andClaude Opus 5.5 68511b285a 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 <noreply@anthropic.com>
2026-11-19 05:30:26 +00:00
ee6aaf25d2 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 <noreply@anthropic.com>
2026-11-19 05:25:55 +00:00
6 changed files with 287 additions and 28 deletions
@@ -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,7 +866,7 @@ 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();
});
@@ -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 = `<!doctype html><html><body>${sections
.map((i) => `<h2>Section ${i}</h2><p>Paragraph ${i}</p>`)
.join("")}</body></html>`;
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<number> {
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<HTMLElement>(".cm-scroller")].find(visible) ?? null;
} else {
scroller =
[
...document.querySelectorAll<HTMLElement>('[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<void>;
}>,
name: string,
content: string,
): Promise<void> {
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<void> {
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<number> {
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<void> {
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);
});
@@ -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 = "<html><body>report</body></html>";
function renderGuard(initialActive: boolean) {
let active = initialActive;
const view = renderHook(() => useHtmlPreviewNavigationGuard(DOCUMENT), {
wrapper: ({ children }: { children: ReactNode }) => (
<RetainedPanelActivity active={active}>{children}</RetainedPanelActivity>
),
});
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);
});
});
@@ -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<string | null>(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],
);
}
+3 -17
View File
@@ -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<string | null>(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 (
<WebView
+67 -9
View File
@@ -6,6 +6,7 @@ import {
useSyncExternalStore,
type ComponentProps,
type ComponentType,
type ReactNode,
} from "react";
import {
useFileText,
@@ -15,6 +16,7 @@ import {
import { Text, View } from "react-native";
import { StyleSheet, withUnistyles } from "react-native-unistyles";
import { useTranslation } from "react-i18next";
import { RetainedPanel } from "@/components/retained-panel";
import { Button } from "@/components/ui/button";
import { isWeb } from "@/constants/platform";
import { useAppSettings } from "@/hooks/use-settings";
@@ -67,7 +69,9 @@ type TextFilePanelProps = PluginFilePanelProps & {
/**
* What the Markdown, HTML and Source panels share: a toolbar over the file's Source view and, when
* the panel passes one, its Preview. Both views show the one read of the file and, while editing, the one editor buffer, so switching
* between them neither re-reads nor loses edits. Edits files up to 1 MiB on web; shows larger files
* between them neither re-reads nor loses edits. Each view stays mounted once shown, so switching
* back also returns to where it was scrolled. The exception is the HTML Preview on iOS: iOS
* replaces the WebView of a hidden view, so the page loads again from the top. Edits files up to 1 MiB on web; shows larger files
* and every file on native read-only, and refuses files above the display budget before reading.
*/
export function TextFilePanel(props: TextFilePanelProps) {
@@ -139,9 +143,17 @@ function ReadonlyTextFile({
view={Preview ? view : undefined}
onViewChange={Preview ? setView : undefined}
/>
{showPreview ? (
<Preview text={text.text} params={params} workspaceId={workspaceId} host={host} />
) : (
{Preview ? (
<RetainedPreview
active={showPreview}
preview={Preview}
text={text.text}
params={params}
workspaceId={workspaceId}
host={host}
/>
) : null}
<RetainedView active={!showPreview}>
<ThemedFileSourceView
content={text.text}
filename={params.path}
@@ -149,7 +161,7 @@ function ReadonlyTextFile({
navigationRevision={revision}
presentation={presentation}
/>
)}
</RetainedView>
</View>
);
}
@@ -237,9 +249,17 @@ function EditableTextFile({
vimMode={showPreview ? null : vimMode}
conflict={conflict}
/>
{showPreview ? (
<Preview text={snapshot.content} params={params} workspaceId={workspaceId} host={host} />
) : (
{Preview ? (
<RetainedPreview
active={showPreview}
preview={Preview}
text={snapshot.content}
params={params}
workspaceId={workspaceId}
host={host}
/>
) : null}
<RetainedView active={!showPreview}>
<SourceEditor
model={model}
filename={params.path}
@@ -249,11 +269,48 @@ function EditableTextFile({
onCursorChange={setCursor}
onVimModeChange={setVimMode}
/>
)}
</RetainedView>
</View>
);
}
/**
* A view of the panel that stays mounted, hidden, while the other view shows, so switching back
* returns to the same scroll offset. It mounts the first time it shows.
*/
function RetainedView({ active, children }: { active: boolean; children: ReactNode }) {
const [shown, setShown] = useState(active);
if (active && !shown) setShown(true);
if (!shown) return null;
return (
<RetainedPanel active={active} style={styles.view}>
{children}
</RetainedPanel>
);
}
/**
* The Preview, retained like the Source. While hidden it keeps the text it last showed, so
* editing in Source does not render the hidden Preview on every change.
*/
function RetainedPreview({
active,
preview: Preview,
text,
params,
workspaceId,
host,
}: TextFilePreviewProps & { active: boolean; preview: ComponentType<TextFilePreviewProps> }) {
const [shownText, setShownText] = useState(text);
if (active && shownText !== text) setShownText(text);
const previewText = active ? text : shownText;
const preview = useMemo(
() => <Preview text={previewText} params={params} workspaceId={workspaceId} host={host} />,
[Preview, previewText, params, workspaceId, host],
);
return <RetainedView active={active}>{preview}</RetainedView>;
}
/** The editor over the panel's buffer. Each mount shows Loading until the editor shows the text. */
function SourceEditor(props: Omit<ComponentProps<typeof ThemedFileEditorView>, "onReady">) {
const [ready, setReady] = useState(false);
@@ -268,6 +325,7 @@ function SourceEditor(props: Omit<ComponentProps<typeof ThemedFileEditorView>, "
const styles = StyleSheet.create((theme) => ({
container: { flex: 1, minHeight: 0 },
view: { minHeight: 0 },
editor: { flex: 1, minHeight: 0 },
centerState: {
flex: 1,