Skip to content

Grid.scrollToItem scrolls an already-visible item when the grid is deep-linked before its first render #10245

Closed

Description

@LiveNathan

Description

Grid.scrollToItem(T) documents that it "Scrolls to the given item unless it is already fully visible", but when a grid is deep-linked on a cold page load — the documented use case of "initialize the scroll position on page load when the grid's selected item is set through a URL parameter" — an item that is already fully visible is scrolled anyway, to the top of the viewport.

The Flow connector only honours the "already visible" escape for a row that is already rendered:

scrollToItem(itemKey: string, ...args: number[]): void {
  const grid = this.#grid;

  const targetRow = grid._getRenderedRows().find((row) => row._item && grid.getItemId(row._item) === itemKey);
  if (targetRow && this.#isRowFullyInViewport(targetRow)) {
    return;
  }

  grid.scrollToIndex(...args);
}

vaadin-grid-flow-parent/vaadin-grid-flow/src/main/resources/META-INF/frontend/vaadin-grid/gridConnector.ts, lines 369–378 on main.

Grid.scrollToItem dispatches that call from scheduleScrollExecution, which runs the action inside beforeClientResponse (Grid.java). On a cold load that fires before the client has rendered any rows, so grid._getRenderedRows() is empty, targetRow is undefined, the visibility check is skipped, and grid.scrollToIndex(index) runs unconditionally.

Since that check is the only thing that makes the "unless it is already fully visible" promise true, a deep-linked item resting inside the initial viewport is forcibly parked at the top of the grid — a visible jump that the API contract says should not happen.

The symptom is easy to miss when testing: for items that genuinely start off-screen, the unconditional scroll produces the expected result, so only items near the start of the data set look broken.

This is still reproducible on main (checked 2026-09-25); the Javadoc at Grid.java line 5316 and the connector logic above are both unchanged.

Expected outcome

grid.scrollToItem(item) should not scroll when item is already fully visible in the viewport — including when the call is made during the same request that first renders the grid, which is the normal shape for resolving a ?focus=<id> URL parameter in beforeEnter.

Either the visibility check should run after the grid's initial render, or the scroll should be re-evaluated once _getRenderedRows() has been populated.

Minimal reproducible example

@Route("grid-focus")
public class GridFocusView extends VerticalLayout implements BeforeEnterObserver {

    private final Grid<String> grid = new Grid<>();

    public GridFocusView() {
        setSizeFull();
        grid.setSizeFull();
        grid.addColumn(s -> s).setHeader("Item");
        // 200 items; a full-height grid renders well over 10 of them initially.
        grid.setItems(IntStream.range(0, 200).mapToObj(i -> "Item " + i).toList());
        add(grid);
    }

    @Override
    public void beforeEnter(BeforeEnterEvent event) {
        // Deep link: /grid-focus?focus=10 — "Item 10" is already fully visible at scroll position 0.
        event.getLocation().getQueryParameters().getSingleParameter("focus")
                .map(Integer::valueOf)
                .ifPresent(index -> grid.scrollToItem("Item " + index));
    }
}

Steps to reproduce

  1. Add the view above to a Vaadin application.
  2. Open http://localhost:8080/grid-focus?focus=10 directly (a full page load, not a client-side navigation after the grid has already rendered).
  3. Observe that the grid scrolls so that "Item 10" sits at the top of the viewport, even though it was already fully visible at scroll position 0.

The size of the unwanted jump equals the item's distance from the top of the data set, so choosing a larger index that is still inside the initial viewport (e.g. ?focus=20 in a tall grid) makes it obvious. Navigating to the same URL while the view is already open and rendered does not reproduce it, because _getRenderedRows() is then populated and the guard fires.

Environment

Vaadin version(s): 25.2.8 (vaadin-grid-flow 25.2.8, Flow 25.2.8)
OS: macOS

Reporter's application is Vaadin 25.2.8 + Spring Boot; the trigger is a readiness-report page linking to production-schedule/:showBookId?focus=<scheduleRowId>, where the receiving view resolves the parameter in beforeEnter and calls Grid.scrollToItem. The root cause is in the connector's pre-render guard and is therefore not specific to that application or to the browser used.

Activity

  1. yuriy-fix commented on Sep 28, 2026

    @yuriy-fix
    Contributor

    Thank you for the issue!
    It can be considered as a bug since the scrolling behavior is not intended in this case.

  2. yuriy-fix commented on Sep 28, 2026

    @yuriy-fix
    Contributor

    @claude, please attempt fixing it

  3. claude commented on Sep 28, 2026

    @claude

    Claude finished @yuriy-fix's task in 6m 17s —— View job • claude/issue-10245-20260928-0717 • Create PR ➔


    Fix: scrollToItem scrolls a visible item on first render

    • Investigate connector scrollToItem and Java scheduleScrollExecution
    • Determine how to defer the visibility check until after first render
    • Implement the fix
    • Add WTR test for the cold-load scenario
    • Build & run tests (WTR)
    • Commit & push

    Root cause: Grid.scrollToItem dispatches the connector call from scheduleScrollExecution, which runs inside beforeClientResponse. On a cold page load (e.g. resolving a ?focus=<id> deep link in beforeEnter) this fires before the client renders any rows. grid._getRenderedRows() is then empty, so the "already fully visible" guard cannot fire and grid.scrollToIndex(index) runs unconditionally — parking an already-visible item at the top.

    Fix (gridConnector.ts): when no rows are rendered yet, defer the visibility check to requestAnimationFrame until the first render populates _getRenderedRows(), then apply the same guard. When rows already exist, behavior is unchanged (immediate check).

    Tests: Added grid-connector-scroll-to-item.test.ts case that reproduces the cold load — a fresh grid with _getRenderedRows().length === 0 at call time — and asserts the grid does not scroll (scrollTop stays 0) when the deep-linked item is already visible. All 4 scroll-to-item WTR tests and the tree-grid scroll tests pass. Confirmed the new test fails without the fix (grid scrolled to scrollTop 360).

    · Branch: claude/issue-10245-20260928-0717

  4. web-padawan commented on Sep 28, 2026

    @web-padawan
    Member

    Warning

    Automated reproduction — produced by the Claude Code repro skill. Needs human verification.
    The steps, verdict, and root-cause pointer below were generated automatically and must be confirmed by a human before being treated as authoritative.

    • Verdict: reproduced
    • Hypothesis tested: The bug is the connector's "already fully visible" guard in scrollToItem being skipped, triggered by calling Grid.scrollToItem in the same round trip that first renders the grid (no rows rendered yet), observable as a non-zero scrollTop with the target row at the top even though it was inside the initial viewport.
    • Regression?: not a regression (broken since the visibility guard was introduced in refactor!: skip scrolling if item is already fully visible #8332, 25.0.0)
    • Fixed by: n/a
    • Duplicate of: none found
    • Branch: repro/10245 — pushed to vaadin/flow-components
    • Reproduced on: flow-components @ main (25.4-SNAPSHOT, 31c6ca7)
    • Present on main?: yes (still broken)
    • Theme / Browser: Lumo / Chromium (playwright-cli)
    • Screenshot (static bug): Cold load of ?focus=10 — Item 10 parked at the top

    Observed behavior

    600px grid, 200 items, 15 rows fully visible at scrollTop 0 (Item 0 – Item 14). Measured in the browser after load:

    Case scrollTop First visible row
    No param (baseline) 0 Item 0
    Cold load ?focus=10 359 Item 10
    Cold load ?focus=20 720 Item 20
    Rendered, then button scrollToItem(Item 10) (control) 0 Item 0

    Item 10 is inside the initial viewport, yet the cold load scrolls it to the top. The same call after the grid has rendered correctly does nothing. Console clean.

    Expected behavior

    scrollToItem(item) does not scroll when item is already fully visible, also when called in the request that first renders the grid (for example resolving a ?focus=<id> parameter in beforeEnter).

    Steps to reproduce

    1. Open http://localhost:8080/repro-10245?focus=10 directly (full page load).
    2. Observe the grid starts at Item 10 (scrollTop about 360), not Item 0.
    3. Open http://localhost:8080/repro-10245, click scrollToItem(Item 10): the grid does not scroll (correct).

    Reproduction

    How to run: mvn package jetty:run -Dvaadin.frontend.hotdeploy=true -am -B -q -DskipTests -pl vaadin-grid-flow-parent/vaadin-grid-flow-integration-tests and open the route below.

    • Route / page: http://localhost:8080/repro-10245?focus=10
    • Scaffold: vaadin-grid-flow-parent/vaadin-grid-flow-integration-tests/src/main/java/com/vaadin/flow/component/grid/it/Repro10245View.java
    @Route("repro-10245")
    public class Repro10245View extends Div implements BeforeEnterObserver {
        private final Grid<String> grid = new Grid<>();
    
        public Repro10245View() {
            grid.setHeight("600px");
            grid.addColumn(s -> s).setHeader("Item");
            grid.setItems(IntStream.range(0, 200).mapToObj(i -> "Item " + i).toList());
            add(new NativeButton("scrollToItem(Item 10)", e -> grid.scrollToItem("Item 10")), grid);
        }
    
        @Override
        public void beforeEnter(BeforeEnterEvent event) {
            event.getLocation().getQueryParameters().getSingleParameter("focus")
                    .map(Integer::valueOf)
                    .ifPresent(index -> grid.scrollToItem("Item " + index));
        }
    }

    Root cause (suspected)

    The connector only skips the scroll when the target row is already rendered. On the first response the grid has no rendered rows yet, so targetRow is undefined and scrollToIndex runs unconditionally:

    scrollToItem(itemKey: string, ...args: number[]): void {
    const grid = this.#grid;
    const targetRow = grid._getRenderedRows().find((row) => row._item && grid.getItemId(row._item) === itemKey);
    if (targetRow && this.#isRowFullyInViewport(targetRow)) {
    return;
    }
    grid.scrollToIndex(...args);
    }

    The call is dispatched from beforeClientResponse, in the same response that creates the grid:

    public void scrollToItem(T item) {
    Objects.requireNonNull(item, "Item to scroll to cannot be null.");
    AbstractDataView<T> dataView = getDataProvider().isInMemory()
    ? getListDataView()
    : getLazyDataView();
    var itemKey = getDataCommunicator().getKeyMapper().key(item);
    int itemIndex = dataView.getItemIndex(item)
    .orElseThrow(() -> new NoSuchElementException(
    "Item to scroll to cannot be found: " + item));
    setViewportRangeByIndex(itemIndex);
    scheduleScrollExecution(() -> getElement()
    .callJsFunction("$connector.scrollToItem", itemKey, itemIndex));
    }

    A possible fix: when no row is rendered yet, defer the check until the first render (for example after requestAnimationFrame / the grid's next render), or treat an unrendered grid at scrollTop 0 by comparing itemIndex against the estimated visible row count.

    Notes

    • Guard added by refactor!: skip scrolling if item is already fully visible #8332 (refactor!: skip scrolling if item is already fully visible), first in 25.0.0. Before that, scrollToItem always scrolled, so the cold-load path simply never got the new behavior.
    • The empty _getRenderedRows() at call time is inferred from the code path and the control case, not instrumented directly.
    • No IT pom changes needed.
  5. vaadin-bot commented on Sep 29, 2026

    @vaadin-bot
    Collaborator

    This ticket/PR has been released with Vaadin 25.4.0-alpha1.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions