diff --git a/packages/dataviews/CHANGELOG.md b/packages/dataviews/CHANGELOG.md index f8f2cd101f4f58..13ee9c5c686de3 100644 --- a/packages/dataviews/CHANGELOG.md +++ b/packages/dataviews/CHANGELOG.md @@ -6,9 +6,11 @@ - DataViews: Add Shift+Click range selection through a shared `useSelectionProps` hook that layouts can adopt, wired up in the table and grid layouts.[#80046](https://github.com/WordPress/gutenberg/pull/80046) - DataViewsPicker: Add Shift+Click range selection to the `picker-table`, `picker-grid`, and `picker-activity` layouts. [#80413](https://github.com/WordPress/gutenberg/pull/80413) +- DataViews: Unload offscreen infinite-scroll items in the list, table, and activity layouts. ### Bug Fix +- DataViewsPicker: Prevent the activity layout from creating an outer scrollbar. - DataForms: Complete the `richtext` control's autocomplete semantics by associating the textbox with its suggestions list for assistive technology. [#80403](https://github.com/WordPress/gutenberg/pull/80403) - DataViews: Fix the `list` layout ignoring the density setting, the refreshing state, and the loading state when `groupBy` is set. [#80255](https://github.com/WordPress/gutenberg/pull/80255) - Fix Dataviews popover hover text color readability issue on WordPress 7.0. [#80105](https://github.com/WordPress/gutenberg/pull/80105) diff --git a/packages/dataviews/src/components/dataviews-layouts/activity/activity-item.tsx b/packages/dataviews/src/components/dataviews-layouts/activity/activity-item.tsx index c1c608225054b1..d455ae5685be16 100644 --- a/packages/dataviews/src/components/dataviews-layouts/activity/activity-item.tsx +++ b/packages/dataviews/src/components/dataviews-layouts/activity/activity-item.tsx @@ -17,6 +17,7 @@ import { Stack, VisuallyHidden } from '@wordpress/ui'; import ItemActions, { PrimaryActions } from '../../dataviews-item-actions'; import DataViewsContext from '../../dataviews-context'; import { ItemClickWrapper } from '../utils/item-click-wrapper'; +import { useIntersectionObserver } from '../utils/use-infinite-scroll'; import type { NormalizedField, ViewActivityProps } from '../../../types'; function ActivityItem< Item >( @@ -51,6 +52,7 @@ function ActivityItem< Item >( const itemRef = useRef< HTMLDivElement >( null ); const registry = useRegistry(); const { paginationInfo } = useContext( DataViewsContext ); + useIntersectionObserver( itemRef, posinset ); const { primaryActions, eligibleActions } = useMemo( () => { // If an action is eligible for all items, doesn't need diff --git a/packages/dataviews/src/components/dataviews-layouts/activity/activity-items.tsx b/packages/dataviews/src/components/dataviews-layouts/activity/activity-items.tsx index b9e52e15e534f0..3dccc1794a19e6 100644 --- a/packages/dataviews/src/components/dataviews-layouts/activity/activity-items.tsx +++ b/packages/dataviews/src/components/dataviews-layouts/activity/activity-items.tsx @@ -4,14 +4,18 @@ import ActivityItem from './activity-item'; import type { ViewActivityProps } from '../../../types'; +type ActivityItemsProps< Item > = ViewActivityProps< Item > & { + isInfiniteScroll?: boolean; +}; + function isDefined< T >( item: T | undefined ): item is T { return !! item; } export default function ActivityItems< Item >( - props: ViewActivityProps< Item > + props: ActivityItemsProps< Item > ) { - const { data, fields, getItemId, view } = props; + const { data, fields, getItemId, isInfiniteScroll, view } = props; // Determine which fields to display based on view configuration const titleField = fields.find( ( field ) => field.id === view.titleField ); @@ -23,7 +27,8 @@ export default function ActivityItems< Item >( .map( ( fieldId ) => fields.find( ( f ) => fieldId === f.id ) ) .filter( isDefined ); - return data.map( ( item, index ) => { + return data.map( ( item ) => { + const { position: posinset } = item as { position?: number }; return ( ( titleField={ titleField } descriptionField={ descriptionField } otherFields={ otherFields } - posinset={ view.infiniteScrollEnabled ? index + 1 : undefined } + posinset={ isInfiniteScroll ? posinset : undefined } /> ); } ); diff --git a/packages/dataviews/src/components/dataviews-layouts/activity/index.tsx b/packages/dataviews/src/components/dataviews-layouts/activity/index.tsx index 8b7f5069a5d06b..c7ea64785d716f 100644 --- a/packages/dataviews/src/components/dataviews-layouts/activity/index.tsx +++ b/packages/dataviews/src/components/dataviews-layouts/activity/index.tsx @@ -91,11 +91,14 @@ export default function ViewActivity< Item >( <>
- { ...props } /> + + { ...props } + isInfiniteScroll={ isInfiniteScroll } + />
{ isInfiniteScroll && isLoading && (

diff --git a/packages/dataviews/src/components/dataviews-layouts/activity/style.scss b/packages/dataviews/src/components/dataviews-layouts/activity/style.scss index 795015c4cafd80..e64eee6683457e 100644 --- a/packages/dataviews/src/components/dataviews-layouts/activity/style.scss +++ b/packages/dataviews/src/components/dataviews-layouts/activity/style.scss @@ -1,6 +1,7 @@ @use "../../../dataviews/style" as *; .dataviews-view-activity { + position: relative; margin: 0 0 auto; padding: 0 var(--wpds-dimension-padding-2xl); diff --git a/packages/dataviews/src/components/dataviews-layouts/list/index.tsx b/packages/dataviews/src/components/dataviews-layouts/list/index.tsx index 7ce85a02d89278..898bea91046b08 100644 --- a/packages/dataviews/src/components/dataviews-layouts/list/index.tsx +++ b/packages/dataviews/src/components/dataviews-layouts/list/index.tsx @@ -43,6 +43,7 @@ import type { import getDataByGroup from '../utils/get-data-by-group'; import useSelectionProps from '../utils/use-selection-props'; import type { SelectionProps } from '../utils/use-selection-props'; +import { useIntersectionObserver } from '../utils/use-infinite-scroll'; interface ListViewItemProps< Item > { view: ViewListType; @@ -163,6 +164,7 @@ function ListItem< Item >( { const itemRef = useRef< HTMLDivElement >( null ); const labelId = `${ idPrefix }-label`; const descriptionId = `${ idPrefix }-description`; + useIntersectionObserver( itemRef, posinset ); const registry = useRegistry(); const [ isHovered, setIsHovered ] = useState( false ); @@ -640,8 +642,11 @@ export default function ViewList< Item >( props: ViewListProps< Item > ) { className={ listClassName } role={ view.infiniteScrollEnabled ? 'feed' : 'grid' } > - { data.map( ( item, index ) => { + { data.map( ( item ) => { const id = generateCompositeItemIdPrefix( item ); + const { position: posinset } = item as { + position?: number; + }; return ( ( props: ViewListProps< Item > ) { onDropdownTriggerKeyDown={ onDropdownTriggerKeyDown } - posinset={ - view.infiniteScrollEnabled - ? index + 1 - : undefined - } + posinset={ isInfiniteScroll ? posinset : undefined } /> ); } ) } diff --git a/packages/dataviews/src/components/dataviews-layouts/picker-activity/style.scss b/packages/dataviews/src/components/dataviews-layouts/picker-activity/style.scss index 573fa49e7d13a8..112591619be30c 100644 --- a/packages/dataviews/src/components/dataviews-layouts/picker-activity/style.scss +++ b/packages/dataviews/src/components/dataviews-layouts/picker-activity/style.scss @@ -1,4 +1,5 @@ .dataviews-view-picker-activity { + position: relative; margin: 0; padding: 0; // Fill the wrapper height so the footer sits at the bottom. diff --git a/packages/dataviews/src/components/dataviews-layouts/table/index.tsx b/packages/dataviews/src/components/dataviews-layouts/table/index.tsx index b9ecb2d1eee8e8..5e16defaa82ae0 100644 --- a/packages/dataviews/src/components/dataviews-layouts/table/index.tsx +++ b/packages/dataviews/src/components/dataviews-layouts/table/index.tsx @@ -13,6 +13,7 @@ import { useContext, useEffect, useId, + useLayoutEffect, useRef, useState, } from '@wordpress/element'; @@ -43,6 +44,7 @@ import ColumnPrimary from './column-primary'; import { useScrollState } from './use-scroll-state'; import getDataByGroup from '../utils/get-data-by-group'; import useSelectionProps from '../utils/use-selection-props'; +import { useIntersectionObserver } from '../utils/use-infinite-scroll'; import { PropertiesSection } from '../../dataviews-view-config/properties-section'; import { useDelayedLoading } from '../../../hooks/use-delayed-loading'; @@ -66,6 +68,98 @@ interface TableColumnFieldProps< Item > { align?: 'start' | 'center' | 'end'; } +/** + * Table rows are not reliable native scroll anchors. Track the row closest to + * the viewport center on every scroll and restore it after observer-driven + * data changes. + * + * @param containerRef The DataViews scroll container. + * @param data The currently rendered table data. + * @param isInfiniteScroll Whether infinite scroll is active. + */ +function useTableScrollAnchor< Item >( + containerRef: React.RefObject< HTMLDivElement | null >, + data: Item[], + isInfiniteScroll: boolean +) { + const anchorRef = useRef< { + posinset: number; + viewportOffset: number; + } | null >( null ); + + useEffect( () => { + const container = containerRef.current; + if ( ! container || ! isInfiniteScroll ) { + anchorRef.current = null; + return; + } + + const captureAnchor = () => { + const containerRect = container.getBoundingClientRect(); + const centerY = containerRect.top + containerRect.height / 2; + const items = Array.from( + container.querySelectorAll( '[aria-posinset]' ) + ).filter( ( item ) => { + const itemRect = item.getBoundingClientRect(); + return ( + itemRect.bottom > containerRect.top && + itemRect.top < containerRect.bottom + ); + } ); + + if ( ! items.length ) { + return; + } + + const anchor = items.reduce( ( closest, item ) => { + const itemRect = item.getBoundingClientRect(); + const closestRect = closest.getBoundingClientRect(); + const distance = Math.abs( + itemRect.top + itemRect.height / 2 - centerY + ); + const closestDistance = Math.abs( + closestRect.top + closestRect.height / 2 - centerY + ); + return distance < closestDistance ? item : closest; + } ); + + anchorRef.current = { + posinset: Number( anchor.getAttribute( 'aria-posinset' ) ), + viewportOffset: + anchor.getBoundingClientRect().top - containerRect.top, + }; + }; + + captureAnchor(); + container.addEventListener( 'scroll', captureAnchor ); + return () => container.removeEventListener( 'scroll', captureAnchor ); + }, [ containerRef, isInfiniteScroll ] ); + + useLayoutEffect( () => { + const container = containerRef.current; + const anchor = anchorRef.current; + if ( ! container || ! isInfiniteScroll || ! anchor ) { + return; + } + + const anchorElement = container.querySelector( + `[aria-posinset="${ anchor.posinset }"]` + ); + if ( ! anchorElement ) { + return; + } + + const currentOffset = + anchorElement.getBoundingClientRect().top - + container.getBoundingClientRect().top; + const scrollAdjustment = currentOffset - anchor.viewportOffset; + + if ( Math.abs( scrollAdjustment ) > 1 ) { + container.scrollTop += scrollAdjustment; + } + }, [ containerRef, data, isInfiniteScroll ] ); +} + interface TableRowProps< Item > { hasBulkActions: boolean; item: Item; @@ -148,6 +242,8 @@ function TableRow< Item >( { showDescription = true, infiniteScrollEnabled, } = view; + const rowRef = useRef< HTMLTableRowElement >( null ); + useIntersectionObserver( rowRef, posinset ); const columns = view.fields ?? []; const hasPrimaryColumn = ( titleField && showTitle ) || @@ -156,6 +252,7 @@ function TableRow< Item >( { return ( ( { ? fields.find( ( f ) => f.id === view.groupBy?.field ) : null; const dataByGroup = groupField ? getDataByGroup( data, groupField ) : null; + const isInfiniteScroll = !! view.infiniteScrollEnabled && ! dataByGroup; + useTableScrollAnchor( containerRef, data, isInfiniteScroll ); // When grouping is enabled the rendered order is by group rather than the // order of `data`; ranges follow what the user sees. const orderedData = dataByGroup @@ -388,7 +487,6 @@ function ViewTable< Item >( { headerMenuRefs.current.delete( column ); } }; - const isInfiniteScroll = view.infiniteScrollEnabled && ! dataByGroup; const isRtl = isRTL(); if ( ! hasData ) { return ( @@ -645,6 +743,9 @@ function ViewTable< Item >( { data.map( ( item, index ) => { const id = getItemId( item ) || index.toString(); + const { position: posinset } = item as { + position?: number; + }; return ( ( { } posinset={ isInfiniteScroll - ? index + 1 + ? posinset : undefined } /> diff --git a/packages/dataviews/src/dataviews-picker/stories/async-infinite-scroll.tsx b/packages/dataviews/src/dataviews-picker/stories/async-infinite-scroll.tsx new file mode 100644 index 00000000000000..fbe9ba40e5b109 --- /dev/null +++ b/packages/dataviews/src/dataviews-picker/stories/async-infinite-scroll.tsx @@ -0,0 +1,137 @@ +/** + * WordPress dependencies + */ +import { useEffect, useMemo, useState } from '@wordpress/element'; + +/** + * Internal dependencies + */ +import DataViewsPicker from '../index'; +import { + LAYOUT_PICKER_ACTIVITY, + LAYOUT_PICKER_GRID, + LAYOUT_PICKER_TABLE, +} from '../../constants'; +import filterSortAndPaginate from '../../utils/filter-sort-and-paginate'; +import type { ActionButton, View } from '../../types'; +import { data as fixtureData, fields, type SpaceObject } from './fixtures'; + +// The fixtures only contain 37 rows; repeat them (with unique ids) so there +// are enough rows to page through several times. +const data = Array.from( { length: 8 }, ( _, batch ) => + fixtureData.map( ( item ) => ( { + ...item, + id: item.id + batch * 1000, + name: { + ...item.name, + title: `${ item.name.title } #${ batch + 1 }`, + }, + } ) ) +).flat(); + +const PAGE = 20; +// Simulated per-page network latency. +const LOAD_DELAY_MS = 800; + +const actions: ActionButton< SpaceObject >[] = [ + { + id: 'cancel', + label: 'Cancel', + callback() {}, + }, + { + id: 'confirm', + label: 'Confirm', + isPrimary: true, + callback() {}, + }, +]; + +/** + * A realistic network-backed infinite-scroll picker: the hook advances + * `view.startPosition`, and the consumer fetches that window asynchronously + * (toggling `isLoading`) while reporting the true server total. + */ +const AsyncInfiniteScroll = () => { + const [ view, setView ] = useState< View >( { + type: LAYOUT_PICKER_GRID, + search: '', + startPosition: 1, + perPage: PAGE, + filters: [], + fields: [ 'satellites' ], + titleField: 'title', + descriptionField: 'description', + mediaField: 'image', + infiniteScrollEnabled: true, + } ); + const [ selection, setSelection ] = useState< string[] >( [] ); + + // The "server": how many rows have been delivered so far, and whether a + // request for the current window is in flight. + const [ loadedCount, setLoadedCount ] = useState( PAGE ); + const [ isLoading, setIsLoading ] = useState( false ); + + const startPosition = view.startPosition ?? 1; + const perPage = view.perPage ?? PAGE; + // Rows required to fill the window the hook is currently asking for. + const needed = Math.min( startPosition - 1 + perPage, data.length ); + + useEffect( () => { + if ( needed <= loadedCount ) { + return undefined; + } + setIsLoading( true ); + const timer = setTimeout( () => { + setLoadedCount( needed ); + setIsLoading( false ); + }, LOAD_DELAY_MS ); + return () => clearTimeout( timer ); + }, [ needed, loadedCount ] ); + + const loadedData = useMemo( + () => data.slice( 0, loadedCount ), + [ loadedCount ] + ); + const { data: shownData, paginationInfo } = useMemo( + () => filterSortAndPaginate( loadedData, view, fields ), + [ loadedData, view ] + ); + // Report the true server total (not just what's loaded) so infinite scroll + // keeps requesting until the dataset is exhausted. + const serverPaginationInfo = useMemo( + () => ( { ...paginationInfo, totalItems: data.length } ), + [ paginationInfo ] + ); + + return ( + <> + + item.id.toString() } + paginationInfo={ serverPaginationInfo } + data={ shownData } + view={ view } + fields={ fields } + onChangeView={ setView } + isLoading={ isLoading } + defaultLayouts={ { + [ LAYOUT_PICKER_GRID ]: true, + [ LAYOUT_PICKER_TABLE ]: true, + [ LAYOUT_PICKER_ACTIVITY ]: true, + } } + itemListLabel="Galactic Bodies" + /> + + ); +}; + +export default AsyncInfiniteScroll; diff --git a/packages/dataviews/src/dataviews-picker/stories/index.story.tsx b/packages/dataviews/src/dataviews-picker/stories/index.story.tsx index 628088801d5ccb..8acdbc43fd7b4b 100644 --- a/packages/dataviews/src/dataviews-picker/stories/index.story.tsx +++ b/packages/dataviews/src/dataviews-picker/stories/index.story.tsx @@ -18,6 +18,7 @@ import { LAYOUT_PICKER_GRID } from '../../constants'; import filterSortAndPaginate from '../../utils/filter-sort-and-paginate'; import type { ActionButton, View } from '../../types'; import { data, fields, type SpaceObject } from './fixtures'; +import AsyncInfiniteScrollComponent from './async-infinite-scroll'; const meta = { tags: [ 'manifest' ], @@ -220,6 +221,10 @@ export const Default = ( { Default.args = storyArgs; Default.argTypes = storyArgTypes; +export const AsyncInfiniteScroll = { + render: AsyncInfiniteScrollComponent, +}; + export const WithModal = ( { perPageSizes = [ 10, 25, 50, 100 ], isMultiselectable, diff --git a/packages/dataviews/src/dataviews/stories/async-infinite-scroll.tsx b/packages/dataviews/src/dataviews/stories/async-infinite-scroll.tsx index 8efe231ecfd5d6..cb8ea152b75472 100644 --- a/packages/dataviews/src/dataviews/stories/async-infinite-scroll.tsx +++ b/packages/dataviews/src/dataviews/stories/async-infinite-scroll.tsx @@ -7,7 +7,12 @@ import { useState, useMemo, useEffect } from '@wordpress/element'; * Internal dependencies */ import DataViews from '../index'; -import { LAYOUT_GRID, LAYOUT_LIST, LAYOUT_TABLE } from '../../constants'; +import { + LAYOUT_ACTIVITY, + LAYOUT_GRID, + LAYOUT_LIST, + LAYOUT_TABLE, +} from '../../constants'; import filterSortAndPaginate from '../../utils/filter-sort-and-paginate'; import type { View } from '../../types'; import { actions, data as fixtureData, fields } from './fixtures'; @@ -106,6 +111,7 @@ const AsyncInfiniteScroll = () => { [ LAYOUT_TABLE ]: true, [ LAYOUT_GRID ]: true, [ LAYOUT_LIST ]: true, + [ LAYOUT_ACTIVITY ]: true, } } /> diff --git a/packages/dataviews/src/hooks/use-infinite-scroll.ts b/packages/dataviews/src/hooks/use-infinite-scroll.ts index 35ce32856fc8eb..c9202481107d83 100644 --- a/packages/dataviews/src/hooks/use-infinite-scroll.ts +++ b/packages/dataviews/src/hooks/use-infinite-scroll.ts @@ -14,60 +14,6 @@ import { throttle } from '@wordpress/compose'; */ import type { View } from '../types'; -/** - * Captures an anchor element for scroll position preservation. - * Finds the element closest to the center of the viewport and stores its position. - * - * @param container The scrollable container element. - * @param anchorElementRef Ref to store the anchor element data. - * @param direction The scroll direction ('up' or 'down'). - * @return Whether an anchor element was successfully captured. - */ -function captureAnchorElement( - container: HTMLElement, - anchorElementRef: React.MutableRefObject< { - posinset: number; - viewportOffset: number; - scrollTop: number; - direction: 'up' | 'down' | null; - } | null >, - direction: 'up' | 'down' -): boolean { - // Find a visible element to use as anchor - prefer one in the middle of the viewport - const containerRect = container.getBoundingClientRect(); - const centerY = containerRect.top + containerRect.height / 2; - - // Query all items with aria-posinset and find the one closest to center - const items = Array.from( container.querySelectorAll( '[aria-posinset]' ) ); - - if ( items.length === 0 ) { - return false; - } - - // Find the item closest to the center of the viewport - const bestAnchor = items.reduce( ( best, item ) => { - const itemRect = item.getBoundingClientRect(); - const itemCenterY = itemRect.top + itemRect.height / 2; - const distance = Math.abs( itemCenterY - centerY ); - - const bestRect = best.getBoundingClientRect(); - const bestCenterY = bestRect.top + bestRect.height / 2; - const bestDistance = Math.abs( bestCenterY - centerY ); - - return distance < bestDistance ? item : best; - } ); - - const posinset = Number( bestAnchor.getAttribute( 'aria-posinset' ) ); - const anchorRect = bestAnchor.getBoundingClientRect(); - anchorElementRef.current = { - posinset, - viewportOffset: anchorRect.top - containerRect.top, - scrollTop: container.scrollTop, - direction, - }; - return true; -} - type UseInfiniteScrollProps = { view: View; onChangeView: ( view: View ) => void; @@ -92,18 +38,13 @@ export function useInfiniteScroll( { containerRef, setVisibleEntries, }: UseInfiniteScrollProps ): UseInfiniteScrollResult { - // Track an anchor element for scroll position preservation - // This approach is robust even when items are added/removed from both ends simultaneously - const anchorElementRef = useRef< { - posinset: number; - viewportOffset: number; - scrollTop: number; - direction: 'up' | 'down' | null; - } | null >( null ); const viewRef = useRef( view ); const isLoadingRef = useRef( isLoading ); const onChangeViewRef = useRef( onChangeView ); const totalItemsRef = useRef( paginationInfo.totalItems ); + // Position of the first rendered item when an earlier page is requested. + // Native scroll anchoring handles prepends except at scrollTop 0. + const prependAnchorRef = useRef< number | null >( null ); useLayoutEffect( () => { viewRef.current = view; @@ -152,47 +93,62 @@ export function useInfiniteScroll( { [ setVisibleEntries ] ); - // Preserve scroll position when items are added or removed during infinite scroll - // Uses anchor element approach: find the same element after render and restore its viewport position + // The browser's native scroll anchoring preserves the viewport when pages + // load and the observer unloads offscreen items. Applying another + // JavaScript adjustment here would double-compensate those removals. + // + // Native anchoring is suppressed at scrollTop 0, so handle only the case + // where an earlier page is prepended while the user remains at the top. useLayoutEffect( () => { const container = containerRef.current; - const anchor = anchorElementRef.current; + const anchorPosinset = prependAnchorRef.current; if ( ! container || ! view.infiniteScrollEnabled || - ! anchor || - isLoading + isLoading || + anchorPosinset === null ) { return; } - // Find the anchor element by its posinset + const firstItem = container.querySelector( '[aria-posinset]' ); + const firstPosinset = firstItem + ? Number( firstItem.getAttribute( 'aria-posinset' ) ) + : null; + + // The prepended page has not rendered yet. + if ( firstPosinset === null || firstPosinset >= anchorPosinset ) { + return; + } + + prependAnchorRef.current = null; + + // Away from the top, native anchoring already compensated the prepend. + if ( container.scrollTop > 2 ) { + return; + } + const anchorElement = container.querySelector( - `[aria-posinset="${ anchor.posinset }"]` + `[aria-posinset="${ anchorPosinset }"]` ); - - if ( anchorElement ) { - const containerRect = container.getBoundingClientRect(); - const anchorRect = anchorElement.getBoundingClientRect(); - const currentOffset = anchorRect.top - containerRect.top; - - // Compensate only for the content shift, not for scrolling the user - // did during an async load. Adding back the scroll delta since capture - // keeps the list from snapping back to the capture-time position. - const scrollAdjustment = - currentOffset - - anchor.viewportOffset + - ( container.scrollTop - anchor.scrollTop ); - - if ( Math.abs( scrollAdjustment ) > 1 ) { - container.scrollTop += scrollAdjustment; - } + if ( ! anchorElement ) { + return; } - // Reset the anchor state now that we've adjusted - anchorElementRef.current = null; - }, [ containerRef, isLoading, view.infiniteScrollEnabled ] ); + const prependedHeight = + anchorElement.getBoundingClientRect().top - + container.getBoundingClientRect().top; + + if ( prependedHeight > 1 ) { + container.scrollTop += prependedHeight; + } + }, [ + containerRef, + isLoading, + view.infiniteScrollEnabled, + view.startPosition, + ] ); // Create and expose a shared IntersectionObserver for provider-level reuse. const intersectionObserverRef = useRef< IntersectionObserver | null >( @@ -264,9 +220,6 @@ export function useInfiniteScroll( { if ( currentEndPosition < totalItems ) { const newStartPosition = currentEndPosition; - // Capture anchor element for scroll position preservation - captureAnchorElement( target, anchorElementRef, 'down' ); - onChangeViewRef.current( { ...currentView, startPosition: newStartPosition, @@ -286,8 +239,10 @@ export function useInfiniteScroll( { ? 1 : calculatedStartPosition; - // Capture anchor element for scroll position preservation - captureAnchorElement( target, anchorElementRef, 'up' ); + const firstItem = target.querySelector( '[aria-posinset]' ); + prependAnchorRef.current = firstItem + ? Number( firstItem.getAttribute( 'aria-posinset' ) ) + : null; onChangeViewRef.current( { ...currentView,