Repository navigation
feat(editor): preserve PDF scroll position across tab switches - #12163
Conversation
PDFs snapped back to page 1 on every tab switch — the one scrollable
editor viewer never wired into the shared scroll cache.
A raw scrollTop is the wrong unit here: PdfViewer resets zoom to
page-width on each mount, and page-width resolves to a different
absolute scale for a different container width, so a cached pixel
offset restores to the wrong place. Store the pdf.js location
({ pageNumber, top, left }) instead — PDF user space, scale
independent — and restore via scrollPageIntoView with the same XYZ
destination pdf.js uses for its own scale-change restore.
Scoped to the single-pane edit path: diff and conflict-review mount
several viewers on one path, so they pass no key and keep no memory.
Closes #12117
pdf.js dispatches the init `updateviewarea` synchronously from `update()` right after the `pagesinit` handler, so arming there recorded the restore's own provisional landing. On a mixed-page-size document that landing uses page-1 geometry and is wrong, and a tab switch before `pagesloaded` flushed it over the good cached position. Arm at the first of `pagesloaded` or first user input instead; arm immediately only when nothing was cached. If neither ever happens the recorder never arms and the cached position survives untouched, which is correct because the reader never moved. Co-authored-by: Orca <[email protected]>
Two defects in the restore half, both from calling scrollPageIntoView outside pdf.js's own scale-update path. `#scrollIntoView` nulls `_location` when `currentScaleValue` is unset, and it stays unset because 'page-width' resolves against a page list that is still empty at load. At `pagesinit` that is harmless (`_location` is already null and the init `update()` repopulates it), but the `pagesloaded` re-apply runs with a live `_location` and nothing recomputes it — on a uniform-page document the re-apply moves nothing, so no scroll event fires. The next zoom then found no location, fell back to the page top, and the recorder persisted that page-top position over the reader's offset. Call `update()` after the re-apply to recompute it. The user-moved guard also missed find: `PDFFindController` scrolls to a match programmatically, and the find bar is not inside the watched container, so neither the input listeners nor the arm gate saw a search. Searching during the pagesinit-to-pagesloaded window yanked the reader back to the cached page. Treat a 'find' dispatch as reader movement. Co-authored-by: Orca <[email protected]>
The key's journey from EditorContent through ImageViewer to PdfViewer had no coverage, so dropping the prop anywhere along it would have shipped as silently amnesiac scrolling with a green suite. Assert both directions: forwarded when supplied, null when omitted. Verified the tests fail when the forwarding is removed. Also pin the trailing-from-first-record debounce, which every existing test advanced past and so could be mutated into a restarting debounce undetected, and delete the `timers` injection seam — it had no callers, so only its two fallbacks ever ran. Co-authored-by: Orca <[email protected]>
Editors in background worktrees stay mounted under display:none so their layouts survive worktree switches. There the container has no layout box, so pdf.js bails out of scrollPageIntoView on a null offsetParent and update() early-returns with zero visible pages, leaving its location null. Arming anyway meant the reader's first zoom after switching to that worktree scrolled to the page top and persisted it over the cached position — turning a pane that merely failed to restore into one that destroys the saved position. Stay disarmed and keep the input watcher attached while the container has no height, so the cached entry survives until the reader is actually looking at the pane. A pane that gains layout between pagesinit and pagesloaded still restores normally. Co-authored-by: Orca <[email protected]>
|
Caution Review failedThe pull request is closed. ℹ️ Recent review info⚙️ Run configurationConfiguration used: Repository UI Review profile: CHILL Plan: Pro Plus Run ID: 📒 Files selected for processing (1)
📝 WalkthroughWalkthroughThe change adds PDF view-position caching with page and coordinate data. It validates, clamps, restores, and debounces PDF positions. Editor instances receive scoped cache keys through 🚥 Pre-merge checks | ✅ 3 | ❌ 2❌ Failed checks (2 warnings)
✅ Passed checks (3 passed)
✨ Finishing Touches📝 Generate docstrings
Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out. Comment |
There was a problem hiding this comment.
Actionable comments posted: 1
🧹 Nitpick comments (1)
src/renderer/src/components/editor/EditorContent.tsx (1)
183-188: 📐 Maintainability & Code Quality | 🔵 Trivial | 💤 Low valueCorrect the comment: the scoped branch also gets PDF scroll memory.
The comment states that only the single-pane edit path gets PDF scroll memory. The expression also builds a pane-scoped key for the multi-pane edit path, and line 753 passes it. The real distinction is that the diff and conflict-review
ImageViewercall sites pass no key at all.♻️ Proposed comment fix
- // Why: only the single-pane edit path gets PDF scroll memory — the diff and - // conflict-review paths mount several viewers on one path (see PdfViewer). + // Why: scoped per pane so two panes on one path keep separate positions. The + // diff and conflict-review call sites pass no key, so they opt out entirely.
ℹ️ Review info
⚙️ Run configuration
Configuration used: Repository UI
Review profile: CHILL
Plan: Pro Plus
Run ID: cdc2c8d4-02bf-4bce-999d-2946cbcc6afb
📒 Files selected for processing (11)
src/renderer/src/components/editor/EditorContent.tsxsrc/renderer/src/components/editor/ImageViewer.test.tsxsrc/renderer/src/components/editor/ImageViewer.tsxsrc/renderer/src/components/editor/PdfViewer.tsxsrc/renderer/src/components/editor/closed-editor-tab-cache-sweep.test.tssrc/renderer/src/components/editor/closed-editor-tab-cache-sweep.tssrc/renderer/src/components/editor/pdf-view-position.test.tssrc/renderer/src/components/editor/pdf-view-position.tssrc/renderer/src/components/editor/useClosedEditorTabCleanup.tssrc/renderer/src/lib/scroll-cache.test.tssrc/renderer/src/lib/scroll-cache.ts
Greptile SummaryImplements session-lifetime PDF scroll position preservation across tab and pane switches using an in-memory LRU cache keyed by file path. Positions are stored in PDF user space (
Confidence Score: 5/5Safe to merge. The feature is isolated to in-memory state, all teardown paths are guarded by The implementation handles the four documented self-discovered defects correctly: the arm-gate prevents provisional page-1 positions from overwriting cached ones; the explicit Files Needing Attention: No files require special attention.
|
| Filename | Overview |
|---|---|
| src/renderer/src/components/editor/PdfViewer.tsx | Core scroll-restore logic: arms recorder via pagesinit/pagesloaded/input events, re-applies cached position at pagesloaded, uses ResizeObserver for display:none panes, and correctly guards all paths with cancelled and userMoved flags. |
| src/renderer/src/components/editor/pdf-view-position.ts | Well-tested utility module: validates updateviewarea payloads, builds XYZ scroll destinations with correct ignoreDestinationZoom/allowNegativeOffset flags, clamps page numbers for shrunk documents, and implements the arm-gated trailing-debounce recorder. |
| src/renderer/src/components/editor/closed-editor-tab-cache-sweep.ts | New sweep helper that deletes the unscoped :pdf key and all :: -prefixed pane-scoped entries for a closed file path. Tests cover prefix isolation and no-op on absent keys. |
| src/renderer/src/lib/scroll-cache.ts | Adds PdfViewPosition type and pdfViewPositionCache Map, consistent with the existing module-scoped cache pattern; LRU eviction is applied at write time via setWithLRU. |
| src/renderer/src/components/editor/EditorContent.tsx | Derives pdfViewStateKey (always a non-null string, scoped by viewStateScopeId) and forwards it as scrollCacheKey to ImageViewer — both single-pane and multi-pane edit paths get keyed scroll memory. |
| src/renderer/src/components/editor/ImageViewer.tsx | Adds optional scrollCacheKey prop (null default) and threads it through to PdfViewer only for PDF content; non-PDF branches are unaffected. |
| src/renderer/src/components/editor/useClosedEditorTabCleanup.ts | Adds sweepClosedPdfViewPositions call inside the edit case, consistent with the existing scroll/cursor cleanup pattern for the same file path. |
Sequence Diagram
sequenceDiagram
participant EC as EditorContent
participant IV as ImageViewer
participant PV as PdfViewer
participant Cache as pdfViewPositionCache
participant Rec as PdfViewPositionRecorder
EC->>IV: scrollCacheKey (filePath:pdf)
IV->>PV: scrollCacheKey
Note over PV: pdf.js effect setup
PV->>Rec: createPdfViewPositionRecorder(key)
PV-->>PV: pagesinit event
PV->>Cache: get(scrollCacheKey)
alt cached position exists
Cache-->>PV: "{ pageNumber, top, left }"
PV->>PV: scrollPageIntoView(XYZ destination)
Note over PV: recorder stays disarmed, input watcher armed
else no cached position
PV->>Rec: arm()
end
PV-->>PV: pagesloaded event
alt "container.clientHeight === 0"
PV->>PV: observeVisibility() via ResizeObserver
else container visible
PV->>PV: scrollPageIntoView(destination) if !userMoved
PV->>PV: viewer.update()
PV->>Rec: arm()
end
Note over PV: user scrolls normally
PV-->>PV: updateviewarea event
PV->>Rec: record(location)
Rec->>Cache: setWithLRU after 150ms debounce
Note over PV: tab closed / pane switch
PV->>Rec: dispose() flush pending position
Rec->>Cache: setWithLRU(key, lastPosition)
Note over EC: edit tab closed
EC->>Cache: sweepClosedPdfViewPositions(filePath)
Reviews (2): Last reviewed commit: "defer PDF scroll restore until hidden pa..." | Re-trigger Greptile
Why: a display:none pane can't scroll or update pdf.js's internal location, so the reader's initial zoom persists over the cached position. Use ResizeObserver to detect when the pane regains a layout box, then re-apply the saved scroll.
…yai#12163) * feat(editor): preserve PDF scroll position across tab switches PDFs snapped back to page 1 on every tab switch — the one scrollable editor viewer never wired into the shared scroll cache. A raw scrollTop is the wrong unit here: PdfViewer resets zoom to page-width on each mount, and page-width resolves to a different absolute scale for a different container width, so a cached pixel offset restores to the wrong place. Store the pdf.js location ({ pageNumber, top, left }) instead — PDF user space, scale independent — and restore via scrollPageIntoView with the same XYZ destination pdf.js uses for its own scale-change restore. Scoped to the single-pane edit path: diff and conflict-review mount several viewers on one path, so they pass no key and keep no memory. Closes stablyai#12117 * fix(editor): defer PDF scroll recorder arm until the restore settles pdf.js dispatches the init `updateviewarea` synchronously from `update()` right after the `pagesinit` handler, so arming there recorded the restore's own provisional landing. On a mixed-page-size document that landing uses page-1 geometry and is wrong, and a tab switch before `pagesloaded` flushed it over the good cached position. Arm at the first of `pagesloaded` or first user input instead; arm immediately only when nothing was cached. If neither ever happens the recorder never arms and the cached position survives untouched, which is correct because the reader never moved. Co-authored-by: Orca <[email protected]> * fix(editor): keep pdf.js location live after the PDF scroll re-apply Two defects in the restore half, both from calling scrollPageIntoView outside pdf.js's own scale-update path. `#scrollIntoView` nulls `_location` when `currentScaleValue` is unset, and it stays unset because 'page-width' resolves against a page list that is still empty at load. At `pagesinit` that is harmless (`_location` is already null and the init `update()` repopulates it), but the `pagesloaded` re-apply runs with a live `_location` and nothing recomputes it — on a uniform-page document the re-apply moves nothing, so no scroll event fires. The next zoom then found no location, fell back to the page top, and the recorder persisted that page-top position over the reader's offset. Call `update()` after the re-apply to recompute it. The user-moved guard also missed find: `PDFFindController` scrolls to a match programmatically, and the find bar is not inside the watched container, so neither the input listeners nor the arm gate saw a search. Searching during the pagesinit-to-pagesloaded window yanked the reader back to the cached page. Treat a 'find' dispatch as reader movement. Co-authored-by: Orca <[email protected]> * test(editor): pin the PDF scroll cache wiring and drop a dead seam The key's journey from EditorContent through ImageViewer to PdfViewer had no coverage, so dropping the prop anywhere along it would have shipped as silently amnesiac scrolling with a green suite. Assert both directions: forwarded when supplied, null when omitted. Verified the tests fail when the forwarding is removed. Also pin the trailing-from-first-record debounce, which every existing test advanced past and so could be mutated into a restarting debounce undetected, and delete the `timers` injection seam — it had no callers, so only its two fallbacks ever ran. Co-authored-by: Orca <[email protected]> * fix(editor): do not arm the PDF recorder in a hidden worktree pane Editors in background worktrees stay mounted under display:none so their layouts survive worktree switches. There the container has no layout box, so pdf.js bails out of scrollPageIntoView on a null offsetParent and update() early-returns with zero visible pages, leaving its location null. Arming anyway meant the reader's first zoom after switching to that worktree scrolled to the page top and persisted it over the cached position — turning a pane that merely failed to restore into one that destroys the saved position. Stay disarmed and keep the input watcher attached while the container has no height, so the cached entry survives until the reader is actually looking at the pane. A pane that gains layout between pagesinit and pagesloaded still restores normally. Co-authored-by: Orca <[email protected]> * defer PDF scroll restore until hidden pane becomes visible Why: a display:none pane can't scroll or update pdf.js's internal location, so the reader's initial zoom persists over the cached position. Use ResizeObserver to detect when the pane regains a layout box, then re-apply the saved scroll. --------- Co-authored-by: Orca <[email protected]>
Closes #12117
PDF scroll position was lost on every tab switch and reset to the start of the file. This restores the reader to where they were.
Scope
Session-lifetime only: positions live in an in-memory LRU keyed by file path, survive tab switches, close-and-reopen, and pane switches, and are cleared on restart. No disk or schema work. Precision is page plus intra-page offset, so a reader mid-page lands mid-page.
Out of scope: scroll memory for images, markdown preview, or other viewers; any change to zoom behavior.
Design
Position is stored in PDF user space, not as
scrollTop. pdf.js rebuilds page layout at a scale derived from container width, so a pixel offset restores to the wrong place at a different pane width. The stored{ pageNumber, top, left }is scale-independent. Restore builds the same XYZ destination pdf.js uses for its own scale-change restore, withignoreDestinationZoomso the destination cannot overwrite the reader's zoom andallowNegativeOffsetso a position in an inter-page gap isn't clamped to the page top.Restore happens at
pagesinit, then once more atpagesloaded.pagesinitlays every page out with page 1's dimensions, so on a mixed-page-size document the first restore lands short.pagesloadedis the first point with real per-page heights, but it can arrive seconds later — so the re-apply is skipped if the reader has moved in the meantime.Keying is opt-in. Only the single-pane edit path passes a
scrollCacheKey. The diff and conflict-review paths mount several viewers on one file path, where a shared key would cross-write, so they pass none. That also makescase 'edit':provably the only cleanup branch that needs the sweep.Review
Three dimensions reviewed across two rounds, which turned up four defects in my own implementation:
scrollPageIntoViewnulls pdf.js's_locationwhencurrentScaleValueis unset. On a uniform-page document the re-apply moves nothing, so no scroll event recomputed it, and the reader's next zoom scrolled to the page top and persisted it over their saved offset. Fixed with an explicitupdate().display:none, where pdf.js can neither scroll nor recompute location. Arming there let a later zoom overwrite the cached position, turning "fails to restore" into "destroys saved state".Coverage: 1056 tests green, plus typecheck, oxlint and oxfmt. The wiring test was verified non-vacuous by deleting the forwarded prop and confirming it fails.
Known limitations
topis not clamped when a document shrinks on disk and has mixed page sizes; the page number is.pagesloadedarrives on page-1 geometry, so the re-applied position can be wrong rather than absent.Pre-existing bugs found, deliberately not fixed
Both are out of scope and reported separately:
applyPdfScalePreferenceis a no-op forpage-width— it runs before pdf.js builds its page list, so#setScaleearly-returns. PDFs open at 100%, not fit-to-width, and the footer reads 100% until the reader zooms. This is also the precondition for the_locationbug above.Made with Orca 🐋