Repository: mui/mui-x
Pull request #16763: [DataGrid] Fix scroll jump with dynamic row height
Author: login: cherniavskii
Labels: name: scope: data grid
description: Changes related to the data grid.
name: plan: Pro
description: Impact at least one Pro user.
name: type: regression
description: A bug, but worse, it used to behave as expected.
name: feature: Row height
description: Related to the data grid Row height features
name: needs cherry-pick
description: The PR should be cherry-picked to master after merge.
name: v7.x
Created: 2025-02-28T10:23:30Z | Merged: 2025-03-03T15:33:38Z

Fixes https://github.com/mui/mui-x/issues/14726


Diff:
diff --git a/packages/x-data-grid/src/hooks/features/rows/useGridRowsMeta.ts b/packages/x-data-grid/src/hooks/features/rows/useGridRowsMeta.ts
index e04789888cdc7..bfc11cc71940c 100644
--- a/packages/x-data-grid/src/hooks/features/rows/useGridRowsMeta.ts
+++ b/packages/x-data-grid/src/hooks/features/rows/useGridRowsMeta.ts
@@ -22,7 +22,7 @@ import {
 } from '../dimensions/gridDimensionsSelectors';
 import { getValidRowHeight, getRowHeightWarning } from './gridRowsUtils';
 import type { HeightEntry } from './gridRowsMetaInterfaces';
-
+import { gridFocusedVirtualCellSelector } from '../virtualization/gridFocusedVirtualCellSelector';
 /* eslint-disable no-underscore-dangle */
 
 export const rowsMetaStateInitializer: GridStateInitializer = (state, props, apiRef) => {
@@ -261,6 +261,13 @@ export const useGridRowsMeta = (
               ? entry.borderBoxSize[0].blockSize
               : entry.contentRect.height;
           const rowId = (entry.target as any).__mui_id;
+          const focusedVirtualRowId = gridFocusedVirtualCellSelector(apiRef)?.id;
+          if (focusedVirtualRowId === rowId && height === 0) {
+            // Focused virtual row has 0 height.
+            // We don't want to store it to avoid scroll jumping.
+            // https://github.com/mui/mui-x/issues/14726
+            return;
+          }
           apiRef.current.unstable_storeRowHeightMeasurement(rowId, height);
         }
         if (!isHeightMetaValid.current) {
diff --git a/test/e2e/fixtures/DataGrid/DynamicRowHeight.tsx b/test/e2e/fixtures/DataGrid/DynamicRowHeight.tsx
new file mode 100644
index 0000000000000..d831e7589c488
--- /dev/null
+++ b/test/e2e/fixtures/DataGrid/DynamicRowHeight.tsx
@@ -0,0 +1,34 @@
+import * as React from 'react';
+import { DataGrid } from '@mui/x-data-grid';
+
+const rows = [
+  { id: 0 },
+  { id: 1 },
+  { id: 2 },
+  { id: 3 },
+  { id: 4 },
+  { id: 5 },
+  { id: 6 },
+  { id: 7 },
+  { id: 8 },
+  { id: 9 },
+  { id: 10 },
+  { id: 11 },
+  { id: 12 },
+  { id: 13 },
+  { id: 14 },
+  { id: 15 },
+  { id: 16 },
+  { id: 17 },
+  { id: 18 },
+  { id: 19 },
+  { id: 20 },
+];
+
+export default function DynamicRowHeight() {
+  return (
+    <div style={{ height: 300, width: 400 }}>
+      <DataGrid rows={rows} columns={[{ field: 'id' }]} getRowHeight={() => 'auto'} />
+    </div>
+  );
+}
diff --git a/test/e2e/index.test.ts b/test/e2e/index.test.ts
index 0b7d61d1158b4..6b6b77b3b49d2 100644
--- a/test/e2e/index.test.ts
+++ b/test/e2e/index.test.ts
@@ -599,6 +599,39 @@ async function initializeEnvironment(
         });
         expect(scrollTop).not.to.equal(0);
       });
+
+      // https://github.com/mui/mui-x/issues/14726
+      it('should not cause scroll jumping when the focused cell is outside of the viewport', async () => {
+        await renderFixture('DataGrid/DynamicRowHeight');
+
+        await page.click('[role="row"][data-id="2"] [role="gridcell"][data-field="id"]');
+
+        const scrollPositions: number[] = [];
+        await page.exposeFunction('storeScrollPosition', async (scrollTop: number) => {
+          scrollPositions.push(scrollTop);
+        });
+        await page.evaluate(() => {
+          const virtualScroller = document.querySelector('.MuiDataGrid-virtualScroller')!;
+          virtualScroller.addEventListener('scroll', () => {
+            // @ts-ignore
+            window.storeScrollPosition(virtualScroller.scrollTop);
+          });
+        });
+
+        await page.mouse.wheel(0, 150);
+        await page.waitForTimeout(500);
+
+        const hadScrollJump = scrollPositions.some((scrollTop, index) => {
+          if (index === 0) {
+            return false;
+          }
+          // When scrolling down, the scrollTop should be always decreasing
+          const prevScrollTop = scrollPositions[index - 1];
+          return scrollTop < prevScrollTop;
+        });
+
+        expect(hadScrollJump).to.equal(false, `Scroll jumped, scrollPositions: ${scrollPositions}`);
+      });
     });
 
     describe('<DatePicker />', () => {


Reviews:
user: login: arminmeh
state: COMMENTED
author_association: CONTRIBUTOR
submitted_at: 2025-03-03T07:52:00Z
user: login: cherniavskii
state: COMMENTED
author_association: MEMBER
submitted_at: 2025-03-03T10:52:21Z
user: login: arminmeh
state: COMMENTED
author_association: CONTRIBUTOR
submitted_at: 2025-03-03T12:11:02Z
user: login: cherniavskii
state: COMMENTED
author_association: MEMBER
submitted_at: 2025-03-03T12:56:41Z
user: login: arminmeh
state: COMMENTED
author_association: CONTRIBUTOR
submitted_at: 2025-03-03T13:28:50Z
user: login: arminmeh
state: APPROVED
author_association: CONTRIBUTOR
submitted_at: 2025-03-03T13:28:56Z

Review comments:
diff_hunk: @@ -599,6 +599,39 @@ async function initializeEnvironment(
         });
         expect(scrollTop).not.to.equal(0);
       });
+
+      // https://github.com/mui/mui-x/issues/14726
+      it('should not cause scroll jumping when the focused cell is outside of the viewport', async () => {
+        await renderFixture('DataGrid/DynamicRowHeight');
+
+        await page.click('[role="row"][data-id="2"] [role="gridcell"][data-field="id"]');
+
+        const scrollPositions: number[] = [];
+        await page.exposeFunction('storeScrollPosition', async (scrollTop: number) => {
+          scrollPositions.push(scrollTop);
+        });
+        await page.evaluate(() => {
+          const virtualScroller = document.querySelector('.MuiDataGrid-virtualScroller')!;
+          virtualScroller.addEventListener('scroll', () => {
+            // @ts-ignore
+            window.storeScrollPosition(virtualScroller.scrollTop);
+          });
+        });
+
+        await page.mouse.wheel(0, 150);
+        await page.waitForTimeout(500);
path: test/e2e/index.test.ts
user: login: arminmeh
body: Can we use `waitForSelector` here?

In the description of `waitForTimeout` it says
>Note that page.waitForTimeout() should only be used for debugging. Tests using the timer in production are going to be flaky. Use signals such as network events, selectors becoming visible and others instead.
created_at: 2025-03-03T07:51:55Z
author_association: CONTRIBUTOR
diff_hunk: @@ -599,6 +599,39 @@ async function initializeEnvironment(
         });
         expect(scrollTop).not.to.equal(0);
       });
+
+      // https://github.com/mui/mui-x/issues/14726
+      it('should not cause scroll jumping when the focused cell is outside of the viewport', async () => {
+        await renderFixture('DataGrid/DynamicRowHeight');
+
+        await page.click('[role="row"][data-id="2"] [role="gridcell"][data-field="id"]');
+
+        const scrollPositions: number[] = [];
+        await page.exposeFunction('storeScrollPosition', async (scrollTop: number) => {
+          scrollPositions.push(scrollTop);
+        });
+        await page.evaluate(() => {
+          const virtualScroller = document.querySelector('.MuiDataGrid-virtualScroller')!;
+          virtualScroller.addEventListener('scroll', () => {
+            // @ts-ignore
+            window.storeScrollPosition(virtualScroller.scrollTop);
+          });
+        });
+
+        await page.mouse.wheel(0, 150);
+        await page.waitForTimeout(500);
path: test/e2e/index.test.ts
user: login: cherniavskii
body: Without a timeout, the assertion will happen before the potential scroll jump, and the test will pass without the fix applied.
I can't see `waitForSelector` as a replacement here, but I'm open for suggestions.
created_at: 2025-03-03T10:52:21Z
author_association: MEMBER
diff_hunk: @@ -599,6 +599,39 @@ async function initializeEnvironment(
         });
         expect(scrollTop).not.to.equal(0);
       });
+
+      // https://github.com/mui/mui-x/issues/14726
+      it('should not cause scroll jumping when the focused cell is outside of the viewport', async () => {
+        await renderFixture('DataGrid/DynamicRowHeight');
+
+        await page.click('[role="row"][data-id="2"] [role="gridcell"][data-field="id"]');
+
+        const scrollPositions: number[] = [];
+        await page.exposeFunction('storeScrollPosition', async (scrollTop: number) => {
+          scrollPositions.push(scrollTop);
+        });
+        await page.evaluate(() => {
+          const virtualScroller = document.querySelector('.MuiDataGrid-virtualScroller')!;
+          virtualScroller.addEventListener('scroll', () => {
+            // @ts-ignore
+            window.storeScrollPosition(virtualScroller.scrollTop);
+          });
+        });
+
+        await page.mouse.wheel(0, 150);
+        await page.waitForTimeout(500);
path: test/e2e/index.test.ts
user: login: arminmeh
body: I didn't test it out, but what I had in mind is to wait for the last row to become attached or first row detached because of the virtualization and assert then
could that work?
created_at: 2025-03-03T12:11:02Z
author_association: CONTRIBUTOR
diff_hunk: @@ -599,6 +599,39 @@ async function initializeEnvironment(
         });
         expect(scrollTop).not.to.equal(0);
       });
+
+      // https://github.com/mui/mui-x/issues/14726
+      it('should not cause scroll jumping when the focused cell is outside of the viewport', async () => {
+        await renderFixture('DataGrid/DynamicRowHeight');
+
+        await page.click('[role="row"][data-id="2"] [role="gridcell"][data-field="id"]');
+
+        const scrollPositions: number[] = [];
+        await page.exposeFunction('storeScrollPosition', async (scrollTop: number) => {
+          scrollPositions.push(scrollTop);
+        });
+        await page.evaluate(() => {
+          const virtualScroller = document.querySelector('.MuiDataGrid-virtualScroller')!;
+          virtualScroller.addEventListener('scroll', () => {
+            // @ts-ignore
+            window.storeScrollPosition(virtualScroller.scrollTop);
+          });
+        });
+
+        await page.mouse.wheel(0, 150);
+        await page.waitForTimeout(500);
path: test/e2e/index.test.ts
user: login: cherniavskii
body: > the last row to become attached or first row detached

Both happen before the scroll jump, so the test will pass without the fix applied.

Perhaps it's possible to make an assertion that will wait for the first row to appear again after scroll with a timeout, and throw if it does appear. But it's not that different from the current solution.
WDYT?
created_at: 2025-03-03T12:56:41Z
author_association: MEMBER
diff_hunk: @@ -599,6 +599,39 @@ async function initializeEnvironment(
         });
         expect(scrollTop).not.to.equal(0);
       });
+
+      // https://github.com/mui/mui-x/issues/14726
+      it('should not cause scroll jumping when the focused cell is outside of the viewport', async () => {
+        await renderFixture('DataGrid/DynamicRowHeight');
+
+        await page.click('[role="row"][data-id="2"] [role="gridcell"][data-field="id"]');
+
+        const scrollPositions: number[] = [];
+        await page.exposeFunction('storeScrollPosition', async (scrollTop: number) => {
+          scrollPositions.push(scrollTop);
+        });
+        await page.evaluate(() => {
+          const virtualScroller = document.querySelector('.MuiDataGrid-virtualScroller')!;
+          virtualScroller.addEventListener('scroll', () => {
+            // @ts-ignore
+            window.storeScrollPosition(virtualScroller.scrollTop);
+          });
+        });
+
+        await page.mouse.wheel(0, 150);
+        await page.waitForTimeout(500);
path: test/e2e/index.test.ts
user: login: arminmeh
body: yes, that would also just spend time waiting for nothing to happen 🙂
in that case, I am fine leave it as is for now
created_at: 2025-03-03T13:28:50Z
author_association: CONTRIBUTOR

PR comments:
user: login: mui-bot
created_at: 2025-02-28T10:27:02Z
body: 
<!--
  0 failure: 
  0 warning: 
  
  1 markdown notices
  DangerID: danger-id-Danger;
-->



**Deploy preview:** <a href="https://deploy-preview-16763--material-ui-x.netlify.app/">https://deploy-preview-16763--material-ui-x.netlify.app/</a>
<p align="right">
  Generated by :no_entry_sign: <a href="https://danger.systems/js">dangerJS</a> against 935e56f7c74dba8166cb110245600395e001d2e9
</p>

author_association: NONE
user: login: arminmeh
created_at: 2025-02-28T14:15:11Z
body: I still see a small movement when you stop scrolling and then hover over another row

Watch row 5

https://github.com/user-attachments/assets/0670aa8c-1dfb-4a45-bb43-c69d218f368c




author_association: CONTRIBUTOR
user: login: cherniavskii
created_at: 2025-02-28T16:28:29Z
body: @arminmeh Seems like an unrelated issue – I can reproduce it without dynamic row height:

https://github.com/user-attachments/assets/52c56d73-95c8-4495-b3f0-153a85d49150

(rows 17-20 move a bit).
author_association: MEMBER
user: login: arminmeh
created_at: 2025-03-03T07:43:38Z
body: > @arminmeh Seems like an unrelated issue – I can reproduce it without dynamic row height:

Found the reason
https://github.com/mui/mui-x/blob/v8.0.0-alpha.13/packages/x-data-grid/src/hooks/features/virtualization/useGridVirtualScroller.tsx#L350

After the scrolling and the timeout, render context changes (adds buffer) and the rows are re-rendered
I will investigate this separately, it should not block this PR


author_association: CONTRIBUTOR
user: login: github-actions[bot]
created_at: 2025-03-03T15:33:53Z
body: Cherry-pick PRs will be created targeting branches: v7.x
author_association: CONTRIBUTOR