GV

GeezerVison

The World Wide Web, restored to 800 pixels of glory.

Home|About|Gaming cabinet|Archives|How it works|Starter sites

On this site

  • Sign in
  • ActionsCI/CD and automation
  • CodespacesCloud development environments
  • All Features
  • Documentation
  • Training
  • Certifications
  • Build with Copilot
  • Customize Copilot
  • Integrations
  • Trending repos
  • GitHub Sponsors
  • Developer articles
  • Enterprises

This view

  • Original page
  • New address

GeezerVison is showing github.com — fix(web): rendered Markdown keeps its scroll position across files an… · patroza/t3code@9c4ab6d

File tree

Expand file treeCollapse file tree
Open diff view settings
Filter options
  • apps/web/src/components/files
    • ChunkedMarkdown.tsx
    • FilePreviewPanel.browser.test.tsx
  • scripts/scenarios
    • rendered-markdown-keeps-reading-position.e2e.ts
Expand file treeCollapse file tree
Open diff view settings
Collapse file

‎apps/web/src/components/files/ChunkedMarkdown.tsx‎

Copy file name to clipboardExpand all lines: apps/web/src/components/files/ChunkedMarkdown.tsx
+44-9Lines changed: 44 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,6 @@
11
import type { ScopedThreadRef } from "@t3tools/contracts";
2-
import { LegendList } from "@legendapp/list/react";
3-
import type { KeyboardEventHandler } from "react";
2+
import { LegendList, type LegendListRef } from "@legendapp/list/react";
3+
import { useRef, type KeyboardEventHandler } from "react";
44

55
import { Spinner } from "~/components/ui/spinner";
66
import { FileMarkdownPreview } from "./FileMarkdownPreview";
@@ -11,6 +11,10 @@ import {
1111
} from "@t3tools/shared/markdownChunks";
1212

1313
const ESTIMATED_LINE_PX = 24;
14+
const MAX_SAVED_POSITIONS = 100;
15+
16+
/** Reading positions outlive the preview, which unmounts when the file or thread changes. */
17+
const savedPositions = new Map<string, { readonly index: number; readonly viewOffset: number }>();
1418

1519
interface ChunkItem {
1620
readonly index: number;
@@ -43,6 +47,22 @@ export function ChunkedMarkdown(props: {
4347
lines += chunk.lines;
4448
start += chunk.text.length + 1;
4549
}
50+
const listRef = useRef<LegendListRef | null>(null);
51+
const positionKey = JSON.stringify([
52+
props.threadRef.environmentId,
53+
props.threadRef.threadId,
54+
props.cwd,
55+
props.relativePath,
56+
]);
57+
const saved = savedPositions.get(positionKey);
58+
// The list applies its initial index once, so wait for the saved chunk to stream in.
59+
const awaitingSaved = props.loading && saved !== undefined && saved.index >= items.length;
60+
const spinner = (
61+
<div className="flex justify-center py-4">
62+
<Spinner size="md" tone="muted" />
63+
</div>
64+
);
65+
if (awaitingSaved) return spinner;
4666
return (
4767
<div
4868
// Clicking the text focuses the preview, so Select All stays inside it.
@@ -58,21 +78,36 @@ export function ChunkedMarkdown(props: {
5878
}}
5979
>
6080
<LegendList<ChunkItem>
81+
// The panel keeps this mounted across threads; the initial index only applies on mount.
82+
key={positionKey}
83+
ref={listRef}
6184
data={items}
85+
{...(saved && {
86+
initialScrollIndex: {
87+
index: Math.min(saved.index, Math.max(items.length - 1, 0)),
88+
viewOffset: saved.viewOffset,
89+
},
90+
})}
91+
onScroll={() => {
92+
const list = listRef.current?.getState();
93+
if (!list) return;
94+
savedPositions.delete(positionKey);
95+
savedPositions.set(positionKey, {
96+
index: list.start,
97+
viewOffset: list.positionAtIndex(list.start) - list.scroll,
98+
});
99+
if (savedPositions.size > MAX_SAVED_POSITIONS) {
100+
savedPositions.delete(savedPositions.keys().next().value!);
101+
}
102+
}}
62103
extraData={props.definitions}
63104
keyExtractor={(item) => String(item.index)}
64105
estimatedItemSize={(lines / Math.max(items.length, 1)) * ESTIMATED_LINE_PX}
65106
drawDistance={800}
66107
recycleItems={false}
67108
className="h-full scrollbar-gutter-both"
68109
contentContainerClassName="py-5"
69-
ListFooterComponent={
70-
props.loading ? (
71-
<div className="flex justify-center py-4">
72-
<Spinner size="md" tone="muted" />
73-
</div>
74-
) : null
75-
}
110+
ListFooterComponent={props.loading ? spinner : null}
76111
renderItem={({ item }) => (
77112
<div className="pb-5">
78113
{item.chunk.text.length > LARGE_MARKDOWN_CHUNK_MAX_CHARS ? (
Collapse file

‎apps/web/src/components/files/FilePreviewPanel.browser.test.tsx‎

Copy file name to clipboardExpand all lines: apps/web/src/components/files/FilePreviewPanel.browser.test.tsx
+117Lines changed: 117 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -174,6 +174,8 @@ vi.mock(import("./projectFilesQueryState"), async (original) => ({
174174
}));
175175

176176
import FilePreviewPanel from "./FilePreviewPanel";
177+
import { ChunkedMarkdown } from "./ChunkedMarkdown";
178+
import { splitMarkdown } from "@t3tools/shared/markdownChunks";
177179

178180
const environmentId = EnvironmentId.make("markdown-preview-test");
179181
const threadRef = { environmentId, threadId: ThreadId.make("thread") };
@@ -806,3 +808,118 @@ describe("rendered Markdown relative images", () => {
806808
);
807809
});
808810
});
811+
812+
describe("rendered Markdown scroll position", () => {
813+
const sections = Array.from(
814+
{ length: 200 },
815+
(_, index) => `## Section ${index}\n\nParagraph ${index}.\n`,
816+
).join("\n");
817+
const scroller = () =>
818+
document.querySelector<HTMLElement>(".scrollbar-gutter-both") ?? expect.unreachable();
819+
/** The first heading in view and its offset from the top of the viewport. */
820+
const readingPosition = () => {
821+
const top = scroller().getBoundingClientRect().top;
822+
for (const heading of scroller().querySelectorAll("h2")) {
823+
const offset = Math.round(heading.getBoundingClientRect().top - top);
824+
if (offset > -100) return { heading: heading.textContent, offset };
825+
}
826+
return null;
827+
};
828+
const scrollDown = async () => {
829+
scroller().scrollTop = 3000;
830+
scroller().dispatchEvent(new Event("scroll"));
831+
await vi.waitFor(() => expect(readingPosition()?.heading).not.toBe("Section 0"));
832+
return readingPosition();
833+
};
834+
const expectReadingPosition = (saved: ReturnType<typeof readingPosition>) =>
835+
vi.waitFor(() => {
836+
const position = readingPosition();
837+
expect(position?.heading).toBe(saved?.heading);
838+
expect(Math.abs((position?.offset ?? 0) - (saved?.offset ?? 0))).toBeLessThanOrEqual(2);
839+
});
840+
const withAppCss = () => {
841+
const style = document.createElement("style");
842+
style.textContent = appCss;
843+
document.head.append(style);
844+
return { [Symbol.dispose]: () => style.remove() };
845+
};
846+
const sized = (children: ReactNode) => (
847+
<div style={{ width: 500, height: 400, display: "flex", flexDirection: "column" }}>
848+
{children}
849+
</div>
850+
);
851+
852+
it("restores each file's reading position after the preview remounts", async () => {
853+
using _settings = setup();
854+
using _style = withAppCss();
855+
const preview = (relativePath: string) => sized(markdownPreview(false, sections, relativePath));
856+
857+
let saved: ReturnType<typeof readingPosition>;
858+
{
859+
await using screen = await render(preview("long.md"));
860+
await expect.element(screen.getByText("Section 0", { exact: true })).toBeInTheDocument();
861+
saved = await scrollDown();
862+
}
863+
{
864+
await using screen = await render(preview("other.md"));
865+
await expect.element(screen.getByText("Section 0", { exact: true })).toBeInTheDocument();
866+
expect(scroller().scrollTop, "another file opens at the top").toBe(0);
867+
}
868+
await using _screen = await render(preview("long.md"));
869+
await expectReadingPosition(saved);
870+
});
871+
872+
it("waits for the saved chunk when a reopened file is still streaming in", async () => {
873+
using _settings = setup();
874+
using _style = withAppCss();
875+
const { chunks, definitions } = splitMarkdown(sections, 200);
876+
const preview = (loaded: number, loading: boolean) =>
877+
sized(
878+
<ChunkedMarkdown
879+
chunks={chunks.slice(0, loaded)}
880+
definitions={definitions}
881+
loading={loading}
882+
cwd="/workspace"
883+
relativePath="streaming.md"
884+
threadRef={threadRef}
885+
workspaceMutationId={null}
886+
/>,
887+
);
888+
889+
let saved: ReturnType<typeof readingPosition>;
890+
{
891+
await using screen = await render(preview(chunks.length, false));
892+
await expect.element(screen.getByText("Section 0", { exact: true })).toBeInTheDocument();
893+
saved = await scrollDown();
894+
}
895+
await using screen = await render(preview(3, true));
896+
expect(document.querySelector(".scrollbar-gutter-both"), "no list before the chunk").toBeNull();
897+
await screen.rerender(preview(chunks.length, false));
898+
await expectReadingPosition(saved);
899+
});
900+
901+
it("keeps each thread's position when the same file stays open across threads", async () => {
902+
using _settings = setup();
903+
using _style = withAppCss();
904+
const { chunks, definitions } = splitMarkdown(sections, 200);
905+
const preview = (threadId: string) =>
906+
sized(
907+
<ChunkedMarkdown
908+
chunks={chunks}
909+
definitions={definitions}
910+
cwd="/workspace"
911+
relativePath="shared.md"
912+
threadRef={{ environmentId, threadId: ThreadId.make(threadId) }}
913+
workspaceMutationId={null}
914+
/>,
915+
);
916+
917+
await using screen = await render(preview("first"));
918+
await expect.element(screen.getByText("Section 0", { exact: true })).toBeInTheDocument();
919+
const saved = await scrollDown();
920+
await screen.rerender(preview("second"));
921+
await vi.waitFor(() => expect(readingPosition()?.heading).toBe("Section 0"));
922+
await screen.rerender(preview("first"));
923+
await expectReadingPosition(saved);
924+
});
925+
});
Collapse file

‎scripts/scenarios/rendered-markdown-keeps-reading-position.e2e.ts‎

Copy file name to clipboard
+88Lines changed: 88 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,88 @@
1+
/// <reference lib="dom" />
2+
// The DOM lib types the functions this scenario runs in the page.
3+
import { expect } from "e2e";
4+
5+
import { test, WEB } from "./t3.ts";
6+
7+
const sections = (name: string) =>
8+
Array.from(
9+
{ length: 120 },
10+
(_, index) =>
11+
`## ${name} section ${index}\n\n${`Reading text for ${name} section ${index}. `.repeat(8)}\n`,
12+
).join("\n");
13+
14+
test(
15+
"Rendered Markdown returns to where each file was being read",
16+
WEB,
17+
async ({ t3, app, browser, screen }) => {
18+
const project = await t3.project("reading", {
19+
"long.md": sections("Long"),
20+
"other.md": sections("Other"),
21+
});
22+
const message =
23+
'See :codex-file-citation{path="long.md"} and :codex-file-citation{path="other.md"}';
24+
const first = await t3.thread({ project, title: "First reading", messages: [message] });
25+
await t3.thread({ project, title: "Second reading", messages: [message] });
26+
27+
/** The first heading at or below the top of the rendered Markdown scroller. */
28+
const reading = () =>
29+
browser.evaluate(() => {
30+
const scroller = [...document.querySelectorAll<HTMLElement>(".scrollbar-gutter-both")].find(
31+
(element) => element.querySelector("h2"),
32+
);
33+
if (!scroller) return null;
34+
const top = scroller.getBoundingClientRect().top;
35+
for (const heading of scroller.querySelectorAll("h2"))
36+
if (heading.getBoundingClientRect().bottom > top) return heading.textContent;
37+
return null;
38+
});
39+
const scrollBy = (pixels: number) =>
40+
browser.evaluate((amount) => {
41+
const scroller = [...document.querySelectorAll<HTMLElement>(".scrollbar-gutter-both")].find(
42+
(element) => element.querySelector("h2"),
43+
);
44+
scroller?.scrollBy(0, amount);
45+
return null;
46+
}, pixels);
47+
const openFile = async (name: string) => {
48+
await screen.getByRole("link", new RegExp(`^${name.replace(".", "\\.")}`)).tap();
49+
};
50+
const expandMessage = () => screen.getByRole("button", /^Agent See/).tap();
51+
52+
await t3.open(first);
53+
await expandMessage();
54+
await openFile("long.md");
55+
await screen.getByRole("button", "Show rendered markdown").tap();
56+
await expect.poll(reading).toBe("Long section 0");
57+
await scrollBy(3000);
58+
await expect.poll(reading).toMatch(/^Long section [1-9]/);
59+
const firstLong = await reading();
60+
61+
await openFile("other.md");
62+
await expect.poll(reading).toBe("Other section 0");
63+
await scrollBy(1600);
64+
await expect.poll(reading).toMatch(/^Other section [1-9]/);
65+
66+
await openFile("long.md");
67+
await app.screenshot("first-thread-long-reopened");
68+
await expect.poll(reading).toBe(firstLong);
69+
70+
// Switch in the app: opening a thread by link reloads the page.
71+
const switchTo = (title: string) => screen.getByRole("button", title, { exact: false }).tap();
72+
await switchTo("Second reading");
73+
await expandMessage();
74+
await openFile("long.md");
75+
await expect.poll(reading).toBe("Long section 0");
76+
await scrollBy(5000);
77+
await expect.poll(reading).toMatch(/^Long section [1-9]/);
78+
const secondLong = await reading();
79+
80+
await switchTo("First reading");
81+
await app.screenshot("first-thread-after-switch");
82+
await expect.poll(reading).toBe(firstLong);
83+
84+
await switchTo("Second reading");
85+
await app.screenshot("second-thread-after-switch");
86+
await expect.poll(reading).toBe(secondLong);
87+
},
88+
);

0 commit comments

Comments
0 (0)
You are visitor 01402792 — GeezerVison does not store the pages you look up.
Best viewed with Netscape Navigator 4.7 or Internet Explorer 6 at 800×600. No cookies required.