Skip to content

Avoid reporting leaving the bottom of the timeline while the window is being resized - #35640

Closed
kaylendog wants to merge 1 commit into
developfrom
fix/kaylendog/flaky-timeline-at-bottom
Closed

kaylendog wants to merge 1 commit into
developfrom
fix/kaylendog/flaky-timeline-at-bottom

Conversation

@kaylendog

@kaylendog kaylendog commented Nov 2, 2026 •

Copy link
Copy Markdown
Contributor

I believe the flaking test in #35449 isn't actually a flaking test, and is indicative of an actual bug with how we handle window resizes and atBottom in TimelineView.

I've attempted to fix this by holding the report used in its computation for a single animation frame, which should prevent spurious flashes of the "jump-to-bottom" button, as well as fixing #35449.

See below for a full problem overview/description - I apologise for the verbosity, but it has taken me a fair old while to understand what on earth Claude has done here, and thought it best to dump my own thinking and context for those who are also uninitiated!

Fixes #35449.

Full PR overview with context (human-written!)

Context

TimelineView tells its view model whenever the reader arrives at or leaves the bottom of the timeline, through onAtBottomStateChange. The view model uses that flag for two things:

reportVisibleState computes this using three figures from the virtualiser:

  • scrollOffset - how far the list is scrolled down;
  • scrollRect.height - the height of the viewport; and
  • getTotalSize() - the summed height of every row

These are combined into atBottom:

const atBottom = scrollOffset + viewportHeight >= totalSize - AT_BOTTOM_THRESHOLD_PX;

However, these three values are maintained by different callbacks, each of which notifies us of a change. This triggers incorrect recomputations of atBottom where the three parameters above refer to different states.

The test in #35449 - keeps a reader at the bottom when the window shrinks and some rows shrink with it - does what's in the name: shrinks the window with rows sized against the viewport, such that both it and the rows change height together. TanStack watches those with two separate ResizeObservers:

  • one on the scroll element (code); and
  • one on the row elements (code).

Each of these notifies us independently when its work is done. We have a patch to @tanstack/virtual, introduced in #35374, of which one hunk is relevant:

@@ -453,7 +470,23 @@ class Virtualizer {
         });
         this.unsubs.push(
           this.options.observeElementRect(this, (rect) => {
+            var _a2;
+            // With anchorTo: "end", keep an end-pinned viewport pinned when the
+            // scroll element shrinks, as resizeItem does when an item grows. The
+            // browser keeps scrollTop, so the end would otherwise drop below the
+            // fold. Judge "pinned" against the size before this change, and never
+            // scroll past the element's real end, except while a clamped write
+            // waits for the sizer (the DOM end is stale then; the retry lands it).
+            // Element-web patch, pending upstream.
+            const prevSize = this.scrollRect !== null ? this.getSize() : null;
+            const wasAtEnd = prevSize !== null && this.options.anchorTo === "end" && ((_a2 = this.scrollState) == null ? void 0 : _a2.behavior) !== "smooth" && this.getVirtualDistanceFromEnd() <= this.options.scrollEndThreshold;
             this.scrollRect = rect;
+            if (wasAtEnd && prevSize > this.getSize()) {
+              const shrink = prevSize - this.getSize();
+              this.applyScrollAdjustment(
+                this._clampedAdjustment !== null ? shrink : Math.min(shrink, this.getDistanceFromEnd())
+              );
+            }
             this.maybeNotify();
           })
         );

This keeps the end in view when the scroll element resizes, which upstream only does when a row resizes. The browser preserves scrollTop rather than the distance from the bottom, so the newest message would otherwise slide under the fold when the composer grows or the window shrinks.

Sequence

Breaking this down step-by-step (partly for my own sanity):

  1. The browser resizes the window and lays out the result. Both the viewport and the vh-sized rows already have their new heights in the DOM, and entries are queued in both observers.
  2. The scroll-element observer runs.
  • scrollRect.height becomes the new, smaller height.
  • The @tanstack__virtual-core@3.patch re-pins the scroll position so the bottom stays in view, adjusting by Math.min(shrink, this.getDistanceFromEnd()).
  • applyScrollAdjustment folds that adjustment into scrollOffset eagerly rather than waiting for the next scroll event, so scrollOffset is current from here on.
  • The observer then notifies us.
  1. reportVisibleState runs, and this is where it goes wrong.
  • scrollRect.height and scrollOffset both describe the resized layout, but getTotalSize() still sums the pre-resize row heights - no row has been re-measured yet.
  • The rows shrank, so that stale total is too large. scrollOffset + viewportHeight falls short of it, and atBottom comes out false.
  • We report that the reader left the bottom.
  1. The row observer runs.
  • Each shrunk row is re-measured, so getTotalSize() drops to match the DOM.
  • The batch finishes by notifying us.
  1. reportVisibleState runs again. All three figures now describe the same layout, so atBottom is true, and we report the reader arriving at a bottom they never left.

In step 3, we are reading figures half way through an update, so we incorrectly flip as bottom to false The user-visible effect is that dragging the window edge briefly shows the jump-to-bottom button, and a message arriving inside that window is counted as unread before the count is cleared again.

Fix

Since there is no consistent set of figures to read, as per above, one solution is to hold the report for a frame.

  • Arriving at the bottom is reported immediately, since this cannot be misread. The figures only ever disagree in the direction of looking further from the bottom than we really are.
  • Leaving the bottom schedules a requestAnimationFrame. If a later pass finds us at the bottom before that frame runs, it is cancelled and nothing is reported at all.

Why not just read the DOM?

This is what Claude first attempted, as v.isAtEnd(AT_BOTTOM_THRESHOLD_PX) looks like it should sidestep the problem by measuring the scroll element directly. However, It doesn't for three reasons:

  • isAtEnd() -> getDistanceFromEnd() -> scrollHeight - clientHeight - scrollOffset.
  • Rows are position: absolute (code), so they contribute nothing to the sizer's height.
  • react-virtual's applyContainerSize writes container.style.height = ${instance.getTotalSize()}px, and does so inside onChange immediately before calling ours.

So scrollHeight is not an independent measurement either, but rather the result of getTotalSize(). This is written to the DOM one statement earlier, carrying exactly the same staleness. The expression is arithmetically equivalent to the one it would replace.

A few alternatives that Claude suggested would genuinely remove the inconsistency:

Both are more complex changes to already difficult-to-understand code, which Claude agrees should be done properly upstream, and I believe should be done by someone smarter than me.

Checklist

  • I have read through review guidelines and CONTRIBUTING.md.
  • I have linked the PR to an issue that describes what needs changing.
  • I have written tests for new code (and old code if feasible).
  • I have ensured new or updated public/exported symbols have accurate TSDoc documentation.
  • I have confirmed linter and other CI checks pass.
  • I have have included screenshots if what the user sees will change
  • I have licensed the changes to Element by completing the Contributor License Agreement (CLA)
  • I will no longer force push to this branch

AI assistance

  • I used AI tools to help create this PR.

Signed-off-by: Skye Elliot <actuallyori@gmail.com>
@langleyd

langleyd commented Nov 6, 2026

Copy link
Copy Markdown
Member

Thanks for taking a look into this. I think the problem is that we are reading tanstack virtual's scroll position(that it has re-read from the DOM since the resize) with it's viewportHeight(which briefly is stale until the ResizeObserver callback fires).

Feels to be like an upstream bug if two values disagree in this onChange handler. For the moment I have added a guard in in element web -> #35727.
But will add it to my list of things that might be able to be upstreamed.

@langleyd

langleyd commented Nov 9, 2026

Copy link
Copy Markdown
Member

In fact I've added an upstream fix for this instead(TanStack/virtual#1378) rather than work around it on the element side and created a PR bump tanstack and add it to the patch.

@kaylendog

Copy link
Copy Markdown
Contributor Author

Closing under the assumption that PR will supersede this one! Please re-open if I'm wrong.

@kaylendog kaylendog closed this Nov 9, 2026

This branch was successfully deployed

3 active deployments
EndToEndTests — 38084e78 Deployed Nov 4, 2026 by github-actions[bot]
Netlify — 38084e78 Deployed Nov 4, 2026 by github-actions[bot]
SharedComponentStorybook — 38084e78 Deployed Nov 4, 2026 by github-actions[bot]
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

Projects

None yet

2 participants