Skip to content

feat(editor): preserve PDF scroll position across tab switches - #12163

Merged
AmethystLiang merged 6 commits into
mainfrom
feature-preserve-pdf-file-scroll-position-after
Aug 3, 2026
Merged

AmethystLiang merged 6 commits into
mainfrom
feature-preserve-pdf-file-scroll-position-after

Conversation

@AmethystLiang

@AmethystLiang AmethystLiang commented Aug 3, 2026 •

Copy link
Copy Markdown
Contributor

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, with ignoreDestinationZoom so the destination cannot overwrite the reader's zoom and allowNegativeOffset so a position in an inter-page gap isn't clamped to the page top.

Restore happens at pagesinit, then once more at pagesloaded. pagesinit lays every page out with page 1's dimensions, so on a mixed-page-size document the first restore lands short. pagesloaded is 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 makes case '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:

  • The recorder armed before the restore settled, so the provisional page-1-geometry landing could be flushed over a good cached position.
  • scrollPageIntoView nulls pdf.js's _location when currentScaleValue is 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 explicit update().
  • The user-moved guard missed find: the find controller scrolls programmatically and the find bar renders outside the watched container, so searching during load yanked the reader back.
  • Editors in background worktrees stay mounted under 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

  • top is not clamped when a document shrinks on disk and has mixed page sizes; the page number is.
  • Renaming an open file from within Orca leaks its entry until LRU eviction — a gap shared with the three existing scroll caches, not introduced here.
  • On documents past pdf.js's lazy-init threshold (>5000 pages), pagesloaded arrives on page-1 geometry, so the re-applied position can be wrong rather than absent.
  • The restore and arm policy live in an effect that isn't unit-testable in this harness; extracting a coordinator is a follow-up.

Pre-existing bugs found, deliberately not fixed

Both are out of scope and reported separately:

  • applyPdfScalePreference is a no-op for page-width — it runs before pdf.js builds its page list, so #setScale early-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 _location bug above.
  • A viewer that fails to decode one PDF can never recover for the next file in that pane: the error state unmounts the container, so the effect returns before clearing the error.

Made with Orca 🐋

AmethystLiang and others added 5 commits August 2, 2026 17:39
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]>
@coderabbitai

coderabbitai Bot commented Aug 3, 2026 •

Copy link
Copy Markdown
Contributor

Review Change Stack

Caution

Review failed

The pull request is closed.

ℹ️ Recent review info
⚙️ Run configuration

Configuration used: Repository UI

Review profile: CHILL

Plan: Pro Plus

Run ID: f5cc28c3-ae24-48d3-9b2c-ec32e9306f69

📥 Commits

Reviewing files that changed from the base of the PR and between 7d7904f and e1330f0.

📒 Files selected for processing (1)
  • src/renderer/src/components/editor/PdfViewer.tsx

📝 Walkthrough

Walkthrough

The 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 ImageViewer and PdfViewer. The viewer handles restoration, user interaction, find navigation, and teardown. Closed edit tabs remove related PDF cache entries. Tests cover storage, recording, viewer prop forwarding, cache eviction, and cleanup.

🚥 Pre-merge checks | ✅ 3 | ❌ 2

❌ Failed checks (2 warnings)

Check name Status Explanation Resolution
Description check ⚠️ Warning The description explains the feature and testing, but it omits required Screenshots, Security Audit, and explicit platform review confirmation. Add the missing template sections, complete the testing checklist, and confirm macOS, Linux, and Windows compatibility was reviewed.
Docstring Coverage ⚠️ Warning Docstring coverage is 55.56% which is insufficient. The required threshold is 80.00%. Write docstrings for the functions missing them to satisfy the coverage threshold.
✅ Passed checks (3 passed)
Check name Status Explanation
Title check ✅ Passed The title clearly describes preserving PDF scroll position across editor tab switches.
Linked Issues check ✅ Passed The implementation directly addresses issue #12117 by preserving PDF positions across tab switches and related editor navigation flows.
Out of Scope Changes check ✅ Passed The changes remain within the stated PDF scroll-position preservation scope and add focused cache, cleanup, wiring, and regression tests.
✨ Finishing Touches
📝 Generate docstrings
  • Create stacked PR
  • Commit on current branch

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.

❤️ Share

Comment @coderabbitai help to get the list of available commands.

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actionable comments posted: 1

🧹 Nitpick comments (1)
src/renderer/src/components/editor/EditorContent.tsx (1)

183-188: 📐 Maintainability & Code Quality | 🔵 Trivial | 💤 Low value

Correct 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 ImageViewer call 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

📥 Commits

Reviewing files that changed from the base of the PR and between 95c431f and 7d7904f.

📒 Files selected for processing (11)
  • src/renderer/src/components/editor/EditorContent.tsx
  • src/renderer/src/components/editor/ImageViewer.test.tsx
  • src/renderer/src/components/editor/ImageViewer.tsx
  • src/renderer/src/components/editor/PdfViewer.tsx
  • src/renderer/src/components/editor/closed-editor-tab-cache-sweep.test.ts
  • src/renderer/src/components/editor/closed-editor-tab-cache-sweep.ts
  • src/renderer/src/components/editor/pdf-view-position.test.ts
  • src/renderer/src/components/editor/pdf-view-position.ts
  • src/renderer/src/components/editor/useClosedEditorTabCleanup.ts
  • src/renderer/src/lib/scroll-cache.test.ts
  • src/renderer/src/lib/scroll-cache.ts

@greptile-apps

greptile-apps Bot commented Aug 3, 2026 •

Copy link
Copy Markdown

Greptile Summary

Implements 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 ({ pageNumber, top, left }) rather than pixel offsets so they survive zoom and pane-width changes.

  • Adds pdfViewPositionCache to the existing scroll-cache module and wires a scrollCacheKey prop through EditorContent → ImageViewer → PdfViewer, where it drives the new record/restore logic hooked into pdf.js pagesinit, pagesloaded, and updateviewarea events.
  • Introduces createPdfViewPositionRecorder — an arm-gated, trailing debounce recorder that prevents provisional page-1 geometry from being flushed over a cached position on mixed-page-size documents.
  • Handles background-worktree (display:none) panes via a ResizeObserver that defers the final restore until the container gains a non-zero height, and correctly sweeps all per-file cache entries when an edit tab is closed.

Confidence Score: 5/5

Safe to merge. The feature is isolated to in-memory state, all teardown paths are guarded by cancelled, and the new cache follows established module patterns.

The implementation handles the four documented self-discovered defects correctly: the arm-gate prevents provisional page-1 positions from overwriting cached ones; the explicit viewer.update() call prevents a null _location from resetting intra-page offset on the next zoom; the find event marks user intent so a mid-load search does not get overridden by pagesloaded; and the ResizeObserver defers restore for display:none panes rather than letting a zoom overwrite the saved state. All race guards (cancelled, userMoved, disposed) are confirmed correct by inspection and covered by the new test suite.

Files Needing Attention: No files require special attention.

Important Files Changed

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)
Loading

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.
@AmethystLiang
AmethystLiang merged commit 45a78e1 into main Aug 3, 2026
@nwparker nwparker mentioned this pull request Aug 3, 2026
enrick-dev pushed a commit to enrick-dev/orca that referenced this pull request Oct 15, 2026
…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]>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

[Feature]: preserve PDF file scroll position after tab switch

1 participant