Repository navigation
fix(web): markdown previews keep their scroll position across tabs #23503
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
base: main
Are you sure you want to change the base?
Changes from all commits
61e0a70
a93fcbd
4dc2355
9190a8e
9e8c5fa
c133071
d2f01ac
ab2b11d
1c8210a
db9bb9d
c461c55
8f8ab26
323ab8f
File filter
Filter by extension
Conversations
Jump to
Diff view
Diff view
There are no files selected for viewing
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -1,10 +1,13 @@ | ||
| import "~/index.css"; | ||
|
|
||
| import { EnvironmentId, ThreadId, type ProjectReadFileResult } from "@t3tools/contracts"; | ||
| import { AsyncResult } from "effect/reactivity"; | ||
| import { describe, expect, it, vi } from "vite-plus/test"; | ||
| import { act, fakeTimers, render } from "../../../test/render"; | ||
|
|
||
| const state = vi.hoisted(() => ({ | ||
| file: null as ProjectReadFileResult | null, | ||
| files: {} as Record<string, ProjectReadFileResult>, | ||
| optimistic: null as ProjectReadFileResult | null, | ||
| writeFile: vi.fn(), | ||
| })); | ||
|
|
@@ -51,8 +54,12 @@ vi.mock(import("~/hooks/useWorkspaceMutationRefresh"), () => ({ | |
| vi.mock(import("./FileBreadcrumbs"), () => ({ FileBreadcrumbs: () => <></> })); | ||
| vi.mock(import("./projectFilesQueryState"), async (original) => ({ | ||
| ...(await original()), | ||
| useProjectFileQuery: () => ({ | ||
| data: state.file, | ||
| useProjectFileQuery: ( | ||
| _environmentId: EnvironmentId, | ||
| _cwd: string, | ||
| relativePath: string | null, | ||
| ) => ({ | ||
| data: (relativePath ? state.files[relativePath] : undefined) ?? state.file, | ||
| error: null, | ||
| isPending: false, | ||
| readError: null, | ||
|
|
@@ -83,6 +90,7 @@ function setup() { | |
| localStorage.setItem(keys[0]!, "false"); | ||
| localStorage.setItem(keys[1]!, "true"); | ||
| state.optimistic = null; | ||
| state.files = {}; | ||
| state.writeFile.mockReset().mockResolvedValue(AsyncResult.success(undefined)); | ||
| return { | ||
| [Symbol.dispose]() { | ||
|
|
@@ -160,3 +168,72 @@ describe("rendered Markdown task saves", () => { | |
| }); | ||
| }); | ||
| }); | ||
|
|
||
| function markdownFile(relativePath: string, contents: string): ProjectReadFileResult { | ||
| return { relativePath, contents, byteLength: contents.length, truncated: false }; | ||
| } | ||
|
|
||
| function scrollPanel(relativePath: string) { | ||
| return ( | ||
| <div className="flex h-[400px] flex-col"> | ||
| <FilePreviewPanel | ||
| environmentId={environmentId} | ||
| cwd="/workspace" | ||
| projectName="Project" | ||
| relativePath={relativePath} | ||
| threadRef={threadRef} | ||
| composerDraftTarget={threadRef} | ||
| keybindings={[]} | ||
| availableEditors={[]} | ||
| openInShortcutEnabled={false} | ||
| revealLine={null} | ||
| revealRequestId={0} | ||
| onOpenFile={vi.fn()} | ||
| onNavigateFolder={vi.fn()} | ||
| folderTrail={undefined} | ||
| onPendingChange={vi.fn()} | ||
| selectedFilePending={false} | ||
| workspaceMutationId={null} | ||
| /> | ||
| </div> | ||
| ); | ||
| } | ||
|
|
||
| function markdownViewport(container: HTMLElement) { | ||
| const element = Array.from( | ||
| container.querySelectorAll<HTMLElement>('[data-slot="scroll-area-viewport"]'), | ||
| ).find((candidate) => candidate.textContent?.includes("paragraph 0.")); | ||
| if (!element) throw new Error("rendered markdown viewport is missing"); | ||
| return element; | ||
| } | ||
|
|
||
| describe("rendered markdown file preview", () => { | ||
| // regression: #22300 switching file tabs reset the rendered markdown scroll to the top | ||
| it("keeps each file's scroll position across file tab switches", async () => { | ||
| using _settings = setup(); | ||
| state.files = { | ||
| "AGENTS.md": markdownFile( | ||
| "AGENTS.md", | ||
| Array.from({ length: 200 }, (_, i) => `Agents paragraph ${i}.`).join("\n\n"), | ||
| ), | ||
| "README.md": markdownFile( | ||
| "README.md", | ||
| Array.from({ length: 200 }, (_, i) => `Readme paragraph ${i}.`).join("\n\n"), | ||
| ), | ||
| }; | ||
|
|
||
| await using screen = await render(scrollPanel("AGENTS.md")); | ||
| await expect.element(screen.getByText("Agents paragraph 199.")).toBeInTheDocument(); | ||
| const agents = markdownViewport(screen.container); | ||
| agents.scrollTop = 1800; | ||
| agents.dispatchEvent(new Event("scroll")); | ||
|
|
||
| await screen.rerender(scrollPanel("README.md")); | ||
| await expect.element(screen.getByText("Readme paragraph 0.")).toBeInTheDocument(); | ||
| expect(markdownViewport(screen.container).scrollTop).toBe(0); | ||
|
|
||
| await screen.rerender(scrollPanel("AGENTS.md")); | ||
| await expect.element(screen.getByText("Agents paragraph 0.")).toBeInTheDocument(); | ||
| await vi.waitFor(() => expect(markdownViewport(screen.container).scrollTop).toBe(1800)); | ||
| }); | ||
| }); | ||
|
Comment on lines
+210
to
+239
Contributor
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more.
|
||
| Original file line number | Diff line number | Diff line change |
|---|---|---|
|
|
@@ -48,7 +48,7 @@ import { mediaFileReference } from "@t3tools/client-runtime/media-reference"; | |
| import { FolderTree, Globe2, WrapTextIcon } from "lucide-react"; | ||
| import { Code2, Eye, Table2 } from "lucide"; | ||
| import * as Schema from "effect/Schema"; | ||
| import { lazy, Suspense, useEffect, useRef, useState } from "react"; | ||
| import { lazy, Suspense, useEffect, useLayoutEffect, useRef, useState } from "react"; | ||
|
|
||
| import { isBrowserPreviewFile, openFileInPreview } from "~/browser/openFileInPreview"; | ||
| import { useAssetUrlRefresh, useAssetUrlState } from "~/assets/assetUrls"; | ||
|
|
@@ -61,6 +61,8 @@ import { useClientSettings } from "~/hooks/useSettings"; | |
| import { useTheme } from "~/hooks/useTheme"; | ||
| import { getLocalStorageItem, setLocalStorageItem, useLocalStorage } from "~/hooks/useLocalStorage"; | ||
| import { resolveDiffThemeName } from "~/lib/diffRendering"; | ||
| import { LRUCache } from "~/lib/lruCache"; | ||
| import { observeResize } from "~/lib/observeResize"; | ||
| import { PREFERRED_HIGHLIGHTER } from "~/lib/syntaxHighlighting"; | ||
| import { cn } from "~/lib/utils"; | ||
| import type { ChatFileAttachment } from "~/types"; | ||
|
|
@@ -927,6 +929,11 @@ function EditableFileSurface({ | |
| ); | ||
| } | ||
|
|
||
| // The rendered surface remounts on every file tab or source toggle, so its offset lives | ||
| // outside React and is written from the scroll listener without re-rendering. | ||
| const renderedMarkdownScrollTops = new LRUCache<number>(200, 200); | ||
| const USER_SCROLL_EVENTS = ["wheel", "touchstart", "pointerdown", "keydown"] as const; | ||
|
|
||
| function RenderedMarkdownSurface({ | ||
| environmentId, | ||
| cwd, | ||
|
|
@@ -951,9 +958,53 @@ function RenderedMarkdownSurface({ | |
| }) { | ||
| const saveTarget = { environmentId, cwd, relativePath }; | ||
| useFileSaveSession(saveTarget, onPendingChange); | ||
| const scrollAreaRef = useRef<HTMLDivElement>(null); | ||
|
|
||
| // oxlint-disable-next-line t3code/no-unreasoned-state-sync -- restores and tracks the viewport's DOM scroll offset while mounted | ||
| useLayoutEffect(() => { | ||
| const root = scrollAreaRef.current; | ||
| const viewport = root?.querySelector<HTMLElement>('[data-slot="scroll-area-viewport"]'); | ||
| if (!root || !viewport) return; | ||
| const key = JSON.stringify([environmentId, cwd, relativePath]); | ||
| const target = renderedMarkdownScrollTops.get(key) ?? 0; | ||
| // Images, math, and code blocks can settle after mount, and the viewport can resize; | ||
| // keep reapplying the offset so a clamped early scrollTop does not overwrite the saved one. | ||
| let restoring = true; | ||
| let unobserve = () => {}; | ||
| // Listen on the root so dragging the scrollbar, a sibling of the viewport, also | ||
| // hands control back to the user. | ||
| const stopRestoring = () => { | ||
| restoring = false; | ||
| unobserve(); | ||
| for (const type of USER_SCROLL_EVENTS) root.removeEventListener(type, stopRestoring); | ||
| }; | ||
| const save = () => { | ||
| if (!restoring) renderedMarkdownScrollTops.set(key, viewport.scrollTop, 1); | ||
| }; | ||
| viewport.scrollTop = target; | ||
| if (Math.abs(viewport.scrollTop - target) < 1) { | ||
| stopRestoring(); | ||
|
Comment on lines
+985
to
+986
Contributor
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more.
|
||
| } else { | ||
| unobserve = observeResize([viewport, ...viewport.children], () => { | ||
| viewport.scrollTop = target; | ||
| if (Math.abs(viewport.scrollTop - target) < 1) stopRestoring(); | ||
| }); | ||
| for (const type of USER_SCROLL_EVENTS) { | ||
| root.addEventListener(type, stopRestoring, { passive: true }); | ||
| } | ||
| } | ||
| viewport.addEventListener("scroll", save, { passive: true }); | ||
| return () => { | ||
| // A scroll in the same frame as the tab switch has not dispatched its event yet. | ||
| // The surface is keyed by file identity, so this runs before its DOM is detached. | ||
| if (viewport.isConnected) save(); | ||
| stopRestoring(); | ||
| viewport.removeEventListener("scroll", save); | ||
| }; | ||
| }, [environmentId, cwd, relativePath]); | ||
|
|
||
| return ( | ||
| <ScrollArea className="min-h-0 flex-1"> | ||
| <ScrollArea ref={scrollAreaRef} className="min-h-0 flex-1"> | ||
| <FileMarkdownPreview | ||
| text={contents} | ||
| cwd={cwd} | ||
|
|
@@ -1494,7 +1545,7 @@ export default function FilePreviewPanel({ | |
| </Suspense> | ||
| ) : isMarkdown && renderMarkdown ? ( | ||
| <RenderedMarkdownSurface | ||
| key={relativePath} | ||
| key={JSON.stringify([environmentId, cwd, relativePath])} | ||
| environmentId={environmentId} | ||
| cwd={cwd} | ||
| relativePath={relativePath} | ||
|
|
||
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Use
vi.waitForfor the viewport assertion.Wrap the
scrollTopassertion invi.waitFor.As per path instructions, “Browser assertions use expect.element or vi.waitFor.”
Source: Path instructions