Repository navigation
fix(web): preserve reading position when side panels resize #41182
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
Changes from all commits
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 | ||||
|---|---|---|---|---|---|---|
| @@ -0,0 +1,118 @@ | ||||||
| import { observeResize } from "./observeResize"; | ||||||
|
|
||||||
| /** Native anchoring keeps a paragraph's start fixed, losing the visible line in a long paragraph. */ | ||||||
| export function preserveReadingPosition( | ||||||
| scroller: HTMLElement, | ||||||
| enabled: () => boolean = () => true, | ||||||
| ): () => void { | ||||||
| let width = scroller.clientWidth; | ||||||
| let anchor: { range: Range; top: number } | null = null; | ||||||
| let frame: number | null = null; | ||||||
|
|
||||||
| const capture = () => { | ||||||
| if (frame !== null || scroller.clientWidth !== width) return; | ||||||
| anchor = null; | ||||||
| if (!enabled() || scroller.scrollTop === 0) return; | ||||||
| const box = scroller.getBoundingClientRect(); | ||||||
| const selection = | ||||||
| scroller.isContentEditable && document.activeElement === scroller | ||||||
| ? document.getSelection() | ||||||
| : null; | ||||||
| if (selection?.isCollapsed && selection.rangeCount > 0) { | ||||||
| const range = selection.getRangeAt(0).cloneRange(); | ||||||
| const rect = range.getBoundingClientRect(); | ||||||
| if ( | ||||||
| scroller.contains(range.startContainer) && | ||||||
| rect.top >= box.top && | ||||||
| rect.bottom <= box.bottom | ||||||
| ) { | ||||||
| anchor = { range, top: rect.top - box.top }; | ||||||
| return; | ||||||
| } | ||||||
| } | ||||||
| // A point near the top captures text rather than the paragraph's bounding box. | ||||||
| const x = box.left + box.width / 2; | ||||||
| // The first point can land in paragraph spacing. Look only within the first few lines. | ||||||
| for (let inset = Math.min(24, box.height / 2); inset < Math.min(64, box.height); inset += 8) { | ||||||
| const y = box.top + inset; | ||||||
| const position = document.caretPositionFromPoint?.(x, y); | ||||||
| const range = document.createRange(); | ||||||
| if (position) { | ||||||
| range.setStart(position.offsetNode, position.offset); | ||||||
| } else { | ||||||
| const fallback = document.caretRangeFromPoint?.(x, y); | ||||||
| if (!fallback) continue; | ||||||
| range.setStart(fallback.startContainer, fallback.startOffset); | ||||||
| } | ||||||
| range.collapse(true); | ||||||
| if ( | ||||||
| !scroller.contains(range.startContainer) || | ||||||
| range.startContainer.nodeType !== Node.TEXT_NODE | ||||||
| ) | ||||||
| continue; | ||||||
| const top = range.getBoundingClientRect().top - box.top; | ||||||
| if (top >= 0 && top < scroller.clientHeight) { | ||||||
| anchor = { range, top }; | ||||||
| break; | ||||||
| } | ||||||
| } | ||||||
| }; | ||||||
| const restore = () => { | ||||||
| if ( | ||||||
| !enabled() || | ||||||
| !anchor || | ||||||
| anchor.range.startContainer.nodeType !== Node.TEXT_NODE || | ||||||
| !scroller.contains(anchor.range.startContainer) | ||||||
| ) | ||||||
| return; | ||||||
| const delta = | ||||||
| anchor.range.getBoundingClientRect().top - scroller.getBoundingClientRect().top - anchor.top; | ||||||
| if (Math.abs(delta) > 0.5) scroller.scrollTop += delta; | ||||||
| }; | ||||||
| const stop = observeResize(scroller, () => { | ||||||
| const nextWidth = scroller.clientWidth; | ||||||
| if (nextWidth === width) { | ||||||
| capture(); | ||||||
| return; | ||||||
| } | ||||||
| width = nextWidth; | ||||||
| restore(); | ||||||
| if (frame !== null) cancelAnimationFrame(frame); | ||||||
| // Virtualized rows can finish measuring in the next frame. Keep the same text anchor then. | ||||||
| frame = requestAnimationFrame(() => { | ||||||
| restore(); | ||||||
| frame = null; | ||||||
| capture(); | ||||||
| }); | ||||||
| }); | ||||||
| scroller.addEventListener("scroll", capture, { passive: true }); | ||||||
| scroller.addEventListener("input", capture); | ||||||
| const captureSelection = () => { | ||||||
| if (document.activeElement === scroller) capture(); | ||||||
| }; | ||||||
| if (scroller.isContentEditable) document.addEventListener("selectionchange", captureSelection); | ||||||
|
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. Keep selection tracking when a read-only editor becomes editable. If the composer mounts with Pointer caret moves are affected. A click that moves the caret, without scrolling, typing, or a key press, does not update the anchor. A later width change then restores the previous text anchor, or nothing when no anchor exists, instead of the caret. Arrow-key moves still update the anchor through the Register Suggested fix
Committable suggestion
|
||||||
| const interrupt = () => { | ||||||
| if (frame !== null) cancelAnimationFrame(frame); | ||||||
| frame = null; | ||||||
| anchor = null; | ||||||
| // Input wins over a pending resize correction; the next frame captures the reader's new place. | ||||||
| frame = requestAnimationFrame(() => { | ||||||
| frame = null; | ||||||
| width = scroller.clientWidth; | ||||||
| capture(); | ||||||
| }); | ||||||
| }; | ||||||
| scroller.addEventListener("wheel", interrupt, { passive: true }); | ||||||
| scroller.addEventListener("touchmove", interrupt, { passive: true }); | ||||||
| scroller.addEventListener("keydown", interrupt); | ||||||
| return () => { | ||||||
| stop(); | ||||||
| if (frame !== null) cancelAnimationFrame(frame); | ||||||
| scroller.removeEventListener("scroll", capture); | ||||||
| scroller.removeEventListener("input", capture); | ||||||
| document.removeEventListener("selectionchange", captureSelection); | ||||||
| scroller.removeEventListener("wheel", interrupt); | ||||||
| scroller.removeEventListener("touchmove", interrupt); | ||||||
| scroller.removeEventListener("keydown", interrupt); | ||||||
| }; | ||||||
| } | ||||||
| Original file line number | Diff line number | Diff line change | ||||||
|---|---|---|---|---|---|---|---|---|
| @@ -0,0 +1,95 @@ | ||||||||
| /// <reference lib="dom" /> | ||||||||
| import { expect } from "e2e"; | ||||||||
|
|
||||||||
| import { test, WEB } from "./t3.ts"; | ||||||||
|
|
||||||||
| const text = Array.from( | ||||||||
| { length: 70 }, | ||||||||
| (_, index) => | ||||||||
| `Sentence ${index + 1}. Opening a side panel should keep the sentence being read visible while the text wraps to the available width. `, | ||||||||
| ).join(""); | ||||||||
|
|
||||||||
| test( | ||||||||
| "Opening a side panel preserves the visible text in the conversation and draft", | ||||||||
| WEB, | ||||||||
| async ({ t3, app, screen, browser }) => { | ||||||||
| const project = await t3.project("demo"); | ||||||||
| const thread = await t3.thread({ | ||||||||
| project, | ||||||||
| title: "Reading position", | ||||||||
| messages: ["Start"], | ||||||||
| model: "multi-turn", | ||||||||
| }); | ||||||||
| await browser.setViewport({ width: 1440, height: 1000 }); | ||||||||
| await t3.open(thread); | ||||||||
| await screen.getByRole("button", "Toggle thread details panel").tap(); | ||||||||
| await screen.getByRole("textbox").fill(text); | ||||||||
| await screen.getByRole("textbox").press("Enter"); | ||||||||
| await screen.getByText("second fixture turn complete", { exact: false }).waitFor(); | ||||||||
| await screen.getByRole("button", "Show full message").tap(); | ||||||||
|
|
||||||||
| const position = (draft: boolean, place: boolean) => | ||||||||
| browser.evaluate( | ||||||||
| async ({ draft, place }) => { | ||||||||
| const scroller = document.querySelector<HTMLElement>( | ||||||||
| draft ? ".composer-tiptap" : ".messages-timeline-scroll", | ||||||||
| )!; | ||||||||
| const content = draft ? scroller : scroller.querySelector("[data-user-message-body]")!; | ||||||||
|
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. Select the long sent message, not the first user-message body.
Suggested fix
Committable suggestion
|
||||||||
| const walker = document.createTreeWalker(content, NodeFilter.SHOW_TEXT); | ||||||||
| let node = walker.nextNode(); | ||||||||
| while (node && (node.textContent?.length ?? 0) < 3000) node = walker.nextNode(); | ||||||||
| if (!node) throw new Error("The long paragraph is not rendered"); | ||||||||
| const range = document.createRange(); | ||||||||
| range.setStart(node, 2500); | ||||||||
| range.collapse(true); | ||||||||
| if (place) { | ||||||||
| scroller.blur(); | ||||||||
| scroller.scrollTop += | ||||||||
| range.getBoundingClientRect().top - scroller.getBoundingClientRect().top - 48; | ||||||||
| } | ||||||||
| await new Promise<void>((resolve) => | ||||||||
| requestAnimationFrame(() => | ||||||||
| requestAnimationFrame(() => requestAnimationFrame(() => resolve())), | ||||||||
| ), | ||||||||
| ); | ||||||||
| return range.getBoundingClientRect().top - scroller.getBoundingClientRect().top; | ||||||||
| }, | ||||||||
| { draft, place }, | ||||||||
| ); | ||||||||
|
|
||||||||
| const point = await browser.evaluate(() => { | ||||||||
| const box = document.querySelector(".messages-timeline-scroll")!.getBoundingClientRect(); | ||||||||
| return { x: box.left + box.width / 2, y: box.top + 150 }; | ||||||||
| }); | ||||||||
| await browser.mouse.move(point.x, point.y); | ||||||||
| await browser.mouse.wheel(0, -800); | ||||||||
| // The wheel's native scroll completes asynchronously before positioning the fixture text. | ||||||||
| await browser.evaluate( | ||||||||
| () => | ||||||||
| new Promise<null>((resolve) => | ||||||||
| requestAnimationFrame(() => requestAnimationFrame(() => resolve(null))), | ||||||||
| ), | ||||||||
| ); | ||||||||
| let timelineBefore = await position(false, true); | ||||||||
| if (Math.abs(timelineBefore - 48) > 2) timelineBefore = await position(false, true); | ||||||||
| if (Math.abs(timelineBefore - 48) > 2) | ||||||||
| throw new Error(`The conversation did not settle at the reading position: ${timelineBefore}`); | ||||||||
| await app.screenshot("conversation-panel-closed"); | ||||||||
| await screen.getByRole("button", "Toggle right panel").tap(); | ||||||||
| const timelineAfter = await position(false, false); | ||||||||
| await app.screenshot("conversation-panel-open"); | ||||||||
| await screen.getByRole("button", "Toggle right panel").tap(); | ||||||||
|
|
||||||||
| await screen.getByRole("textbox").fill(text); | ||||||||
| const draftBefore = await position(true, true); | ||||||||
| if (Math.abs(draftBefore - 48) > 2) | ||||||||
| throw new Error("The draft did not settle at the reading position"); | ||||||||
| await app.screenshot("draft-panel-closed"); | ||||||||
| await screen.getByRole("button", "Toggle right panel").tap(); | ||||||||
| const draftAfter = await position(true, false); | ||||||||
| await app.screenshot("draft-panel-open"); | ||||||||
| expect( | ||||||||
| Math.max(Math.abs(timelineAfter - timelineBefore), Math.abs(draftAfter - draftBefore)), | ||||||||
| ).toBeLessThan(30); | ||||||||
| }, | ||||||||
| ); | ||||||||
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.
Cancel the pending correction when a scrollbar drag starts.
A native scrollbar drag does not fire
wheel,touchmove, orkeydown, sointerruptnever runs for it. Thescrolllistener callscapture, which returns whileframeis pending. The queued frame then callsrestore, which writes the delta from the stored anchor toscrollTop. Any movement the reader made during that frame is reversed.User-initiated scrolling, including a scrollbar drag, must cancel the pending correction, as wheel, touch, and keyboard input already do. Scroll events produced by the helper's own
scrollTopwrites must not cancel it. The choice of input event or origin check is open. The required behavior is that the reader's pending scroll wins over the queued correction.