Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
5 changes: 5 additions & 0 deletions packages/block-editor/CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,11 @@

## Unreleased

### Bug Fixes

- List View: Show every row in view inside panels that change height, and stop Home, End, Page Up and Page Down in other fields from scrolling the list ([#87065](https://github.com/WordPress/gutenberg/pull/87065)).
- List View: Keep focus on a row when it scrolls out of view ([#87065](https://github.com/WordPress/gutenberg/pull/87065)).

## 20.1.0 (2026-11-18)

### Enhancements
Expand Down
9 changes: 6 additions & 3 deletions packages/block-editor/src/components/list-view/branch.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -158,8 +158,9 @@ function ListViewBranch( props: ListViewBranchProps ) {

const isDragged = !! draggedClientIds?.includes( clientId );

const { itemInView } = fixedListWindow;
const blockInView = itemInView( blockListPosition );
const { start, end, focusedClientId } = fixedListWindow;
const blockInView =
blockListPosition >= start && blockListPosition < end;
Comment on lines +162 to +163

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

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

itemInView was a leftover from the useFixedWindowList API. A plain range does the same job and measured no difference in the scroll probe.


const position = index + 1;
const updatedPath =
Expand All @@ -186,10 +187,12 @@ function ListViewBranch( props: ListViewBranchProps ) {
// selected, or a user selects all blocks, while still enabling scroll
// into view behavior when selecting a block or opening the list view.
// The first and last blocks of the list are always rendered, to ensure
// that Home and End keys work as expected.
// that Home and End keys work as expected. The focused block is
// rendered so that scrolling it out of view does not drop focus.
const showBlock =
isDragged ||
blockInView ||
clientId === focusedClientId ||
( isSelected && clientId === selectedClientIds[ 0 ] ) ||
index === 0 ||
index === blockCount - 1;
Expand Down
40 changes: 4 additions & 36 deletions packages/block-editor/src/components/list-view/index.tsx
Original file line number Diff line number Diff line change
@@ -1,11 +1,6 @@
import type { CSSProperties, ForwardedRef, KeyboardEvent } from 'react';
import clsx from 'clsx';
import {
useInstanceId,
useMergeRefs,
useRefEffect,
__experimentalUseFixedWindowList as useFixedWindowList,
} from '@wordpress/compose';
import { useInstanceId, useMergeRefs, useRefEffect } from '@wordpress/compose';
import { isShallowEqual } from '@wordpress/is-shallow-equal';
import { __experimentalTreeGrid as TreeGrid } from '@wordpress/components';
import { VisuallyHidden } from '@wordpress/ui';
Expand Down Expand Up @@ -33,6 +28,7 @@ import useListViewClientIds from './use-list-view-client-ids';
import useListViewCollapseItems from './use-list-view-collapse-items';
import useListViewDropZone from './use-list-view-drop-zone';
import useListViewExpandSelectedItem from './use-list-view-expand-selected-item';
import useListViewWindow from './use-list-view-window';
import { store as blockEditorStore } from '../../store';
import { BlockSettingsDropdown } from '../block-settings-menu/block-settings-dropdown';
import { BLOCK_LIST_ITEM_HEIGHT, focusListItem } from './utils';
Expand Down Expand Up @@ -135,20 +131,6 @@ function ListViewComponent(

const { getBlock, getSelectedBlockClientIds } =
useSelect( blockEditorStore );
const { visibleBlockCount } = useSelect(

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

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

The new hook doesn't need the total row count, so List View no longer subscribes to the global block count.

( select ) => {
const { getGlobalBlockCount, getClientIdsOfDescendants } =
select( blockEditorStore );
const draggedBlockCount =
draggedClientIds?.length > 0
? getClientIdsOfDescendants( draggedClientIds ).length + 1
: 0;
return {
visibleBlockCount: getGlobalBlockCount() - draggedBlockCount,
};
},
[ draggedClientIds ]
);

const { updateBlockSelection } = useBlockSelection();

Expand Down Expand Up @@ -185,6 +167,7 @@ function ListViewComponent(
updateExpansion,
} );
const elementRef = useRef< HTMLElement >( null );
const { ref: listWindowRef, fixedListWindow } = useListViewWindow();

// Allow handling of copy, cut, and paste events.
const clipBoardRef = useClipboardHandler( {
Expand Down Expand Up @@ -248,6 +231,7 @@ function ListViewComponent(
clipBoardRef,
focusOnMountRef,
elementRef,
listWindowRef,
dropZoneRef,
ref,
] );
Expand Down Expand Up @@ -366,22 +350,6 @@ function ListViewComponent(
]
);

const [ fixedListWindow ] = useFixedWindowList(
elementRef,
BLOCK_LIST_ITEM_HEIGHT,
visibleBlockCount,
{
// Ensure that the windowing logic is recalculated when the expanded state changes.
// This is necessary because expanding a collapsed block in a short list view can
// switch the list view to a tall list view with a scrollbar, and vice versa.
// When this happens, the windowing logic needs to be recalculated to ensure that
// the correct number of blocks are rendered, by rechecking for a scroll container.
expandedState: expansionState,
useWindowing: true,
windowOverscan: 40,
}
);

// If there are no blocks to show and we're not showing the appender, do not render the list view.
if ( ! clientIdsTree.length && ! showAppender ) {
return null;
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -253,7 +253,7 @@
}

// List View renders a fixed number of items and relies on each item having a fixed height of 32px.
// If this value changes, we should also change the itemHeight value set in useFixedWindowList.
// If this value changes, we should also change BLOCK_LIST_ITEM_HEIGHT.
// See: https://github.com/WordPress/gutenberg/pull/35230 for additional context.
.block-editor-list-view-block-contents {
display: flex;
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,83 @@
import { describe, expect, it } from 'vitest';
import { render } from 'vitest-browser-react';
import useListViewWindow from '../use-list-view-window';
import { BLOCK_LIST_ITEM_HEIGHT } from '../utils';

const rows = Array.from( { length: 200 }, ( _, index ) => index );

function List() {
const { ref, fixedListWindow } = useListViewWindow();
const { start, end } = fixedListWindow;
return (
<div ref={ ref }>
{ rows.map( ( index ) => (
<div key={ index } style={ { height: BLOCK_LIST_ITEM_HEIGHT } }>
{ index >= start && index < end
? `Row ${ index + 1 }`
: null }
</div>
) ) }
</div>
);
}

// Lets pending scroll events and observer reports from the setup run, so
// that they can't stand in for the update a test is about.
const settle = () =>
new Promise( ( resolve ) =>
requestAnimationFrame( () => requestAnimationFrame( resolve ) )
);

async function renderInPanel() {
const screen = await render(
<div
data-testid="panel"
style={ {
position: 'fixed',
top: 0,
width: 320,
overflow: 'auto',
} }
>
<List />
</div>
);
return { screen, panel: screen.getByTestId( 'panel' ).element() };
}

describe( 'useListViewWindow', () => {
it( 'fills a panel that grows without a window resize', async () => {
const { screen, panel } = await renderInPanel();
panel.style.maxHeight = '200px';
panel.scrollTop = 3000;
await expect
.element( screen.getByText( 'Row 95', { exact: true } ) )
.toBeVisible();
await settle();

panel.style.maxHeight = '3200px';

await expect
.element( screen.getByText( 'Row 190', { exact: true } ) )
.toBeVisible();
} );

it( 'shows the rows in a dropdown opened far down a scrolled page', async () => {
await render( <div style={ { height: '400vh' } } /> );
window.scrollTo( 0, 2 * window.innerHeight );
const { screen, panel } = await renderInPanel();
await settle();
// A popover only starts to clip its content after the first layout.
panel.style.maxHeight = '320px';
await settle();
expect(
screen.getByText( 'Row 100', { exact: true } ).query()
).toBeNull();

panel.scrollTop = 3000;

await expect
.element( screen.getByText( 'Row 100', { exact: true } ) )
.toBeVisible();
} );
} );
4 changes: 3 additions & 1 deletion packages/block-editor/src/components/list-view/types.ts
Original file line number Diff line number Diff line change
Expand Up @@ -197,7 +197,9 @@ export type PrivateListViewProps = ListViewProps & {
* The window of rows that the list view renders.
*/
export type FixedListWindow = {
itemInView: ( index: number ) => boolean;
start: number;
end: number;
focusedClientId?: string;
};

export type ListViewBranchProps = {
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,138 @@
import { useRefEffect } from '@wordpress/compose';
import { getScrollContainer } from '@wordpress/dom';
import { flushSync, useRef, useState } from '@wordpress/element';
import { BLOCK_LIST_ITEM_HEIGHT } from './utils';
import type { FixedListWindow } from './types';

// Every window change re-renders the whole tree, so the window only moves once
// fewer than the minimum rows are left past the viewport, and then moves far
// enough for the next stretch of scrolling.
const MIN_BUFFER_ROWS = 10;
const MAX_BUFFER_ROWS = 40;
Comment on lines +10 to +11

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

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

These were tuned with a perf probe. A minimum of 20 or 30 dropped more frames (28 or 50 against 19). A maximum of 70 halved the dropped frames, but each one got longer (54ms against 42ms).


function getVisibleRows( list: HTMLElement, scrollContainer: Element ) {
const { documentElement } = list.ownerDocument;
const { top, bottom } =
scrollContainer === documentElement
? { top: 0, bottom: documentElement.clientHeight }
: scrollContainer.getBoundingClientRect();
const listTop = list.getBoundingClientRect().top;

return {
first: Math.max(
0,
Math.floor( ( top - listTop ) / BLOCK_LIST_ITEM_HEIGHT )
),
last: Math.max(
0,
Math.ceil( ( bottom - listTop ) / BLOCK_LIST_ITEM_HEIGHT )
),
};
}

function coversRows(
{ start, end }: FixedListWindow,
first: number,
last: number,
spareRows: number
) {
return (
( start === 0 || first - start >= spareRows ) && end - last >= spareRows
);
}

/**
* Tracks which rows of the list view should be rendered.
*
* @return The ref for the list element, and the window of rows to render.
*/
export default function useListViewWindow() {
// The list can't be measured without forcing a layout while it opens, but
// it never shows more rows than fit in the browser window.
const [ fixedListWindow, setFixedListWindow ] = useState< FixedListWindow >(
() => ( {
start: 0,
end: Math.ceil( window.innerHeight / BLOCK_LIST_ITEM_HEIGHT ),
} )
);
Comment on lines +52 to +57

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

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

Reposting, since the earlier comment got detached when this was inlined. Sizing the first window from innerHeight avoids reading layout while the list opens. The cost is about 3 extra rows on a 1080px viewport, which opens about 1ms slower than trunk. 720px and 1440px open faster.

// The listeners below have to know which rows are rendered to tell
// whether a row in view is missing.
const listWindowRef = useRef( fixedListWindow );

const ref = useRefEffect( ( list: HTMLElement ) => {
const { ownerDocument } = list;
const defaultView = ownerDocument.defaultView as Window;
const updateWindow = ( spareRows: number ) => {
const scrollContainer =
getScrollContainer( list ) ?? ownerDocument.documentElement;
const { first, last } = getVisibleRows( list, scrollContainer );
const listWindow = listWindowRef.current;
if ( coversRows( listWindow, first, last, spareRows ) ) {
return;
}

// A row can only be unmounted when the window moves, so this is
// the one moment the focused row has to be known.
const focusedRow =
ownerDocument.activeElement?.closest< HTMLElement >(
'[data-block]'
);
Comment on lines +76 to +79

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

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

The first attempt kept the focused block in state and passed it through context, which re-rendered the whole tree on every focus move. Reading it here costs nothing, since the tree already re-renders when the window moves. A scroll probe measured the same main-thread work with and without the pin. Trunk has the same focus drop, so this isn't a regression fix for the new hook.

const nextWindow = {
start: Math.max( 0, first - MAX_BUFFER_ROWS ),
end: last + MAX_BUFFER_ROWS,
focusedClientId:
focusedRow && list.contains( focusedRow )
? focusedRow.dataset.block
: undefined,
};
listWindowRef.current = nextWindow;

// Scroll events run before paint, so rows that are already in view
// have to be committed here to show up in this frame.
if ( coversRows( listWindow, first, last, 0 ) ) {
setFixedListWindow( nextWindow );
} else {
flushSync( () => setFixedListWindow( nextWindow ) );
}
Comment on lines +92 to +96

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

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

Always using flushSync would let us drop the ref, but it measured worse: jank went up 31%, and dropped frames doubled with a 4x CPU throttle. startTransition for the deferred case made no difference.

};

const fillViewport = () => updateWindow( 0 );
const resizeObserver = new ResizeObserver( fillViewport );

// Scroll events don't bubble, but capturing them here covers whichever
// ancestor ends up scrolling the list.
const onScroll = ( event: Event ) => {
if ( ( event.target as Node ).contains( list ) ) {
updateWindow( MIN_BUFFER_ROWS );
}
};

ownerDocument.addEventListener( 'scroll', onScroll, {
capture: true,
passive: true,
} );
defaultView.addEventListener( 'resize', fillViewport );

// Any ancestor can end up as the scroll container: a popover only
// clips its content after the first layout, and a list starts to
// overflow as it grows. The observer first reports after layout, so
// the first measurement doesn't force one while the list opens.
for (
let node: Element | null = list;
node;
node = node.parentElement
) {
resizeObserver.observe( node );
}

return () => {
resizeObserver.disconnect();
defaultView.removeEventListener( 'resize', fillViewport );
ownerDocument.removeEventListener( 'scroll', onScroll, {
capture: true,
} );
};
}, [] );

return { ref, fixedListWindow };
}
Loading
Loading