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
45 changes: 39 additions & 6 deletions packages/react-aria/src/overlays/useOverlayPosition.ts
Original file line number Diff line number Diff line change
Expand Up @@ -13,7 +13,7 @@
import {addEvent} from '../utils/domHelpers';
import {calculatePosition, getRect, PositionResult} from './calculatePosition';
import {DOMAttributes, RefObject} from '@react-types/shared';
import {getActiveElement, isFocusWithin} from '../utils/shadowdom/DOMFunctions';
import {getActiveElement, isFocusWithin, nodeContains} from '../utils/shadowdom/DOMFunctions';
import {getPropagationTargets} from '../utils/shadowdom/DOMFunctions';
import {useCallback, useEffect, useRef, useState} from 'react';
import {useCloseOnScroll} from './useCloseOnScroll';
Expand Down Expand Up @@ -253,8 +253,9 @@ export function useOverlayPosition(props: AriaPositionProps): PositionAria {
// so it can be restored after repositioning. This way if the overlay height
// changes, the focused element appears to stay in the same position.
let anchor: ScrollAnchor | null = null;
if (scrollRef.current && isFocusWithin(scrollRef.current)) {
let anchorRect = getActiveElement()?.getBoundingClientRect();
let anchorElement = scrollRef.current ? getFocusedElementWithin(scrollRef.current) : null;
if (scrollRef.current && anchorElement) {
let anchorRect = anchorElement.getBoundingClientRect();
let scrollRect = scrollRef.current.getBoundingClientRect();
// Anchor from the top if the offset is in the top half of the scrollable element,
// otherwise anchor from the bottom.
Expand All @@ -268,6 +269,11 @@ export function useOverlayPosition(props: AriaPositionProps): PositionAria {
}
}

// Resetting the max height below can cause the browser to clamp the scroll container's
// scrollTop. Save it so it can be restored if there is no focused element to anchor to.

let savedScrollTop = scrollRef.current?.scrollTop;

// Always reset the overlay's previous max height if not defined by the user so that we can compensate for
// RAC collections populating after a second render and properly set a correct max height + positioning when it populates.
let overlay = overlayRef.current as HTMLElement;
Expand Down Expand Up @@ -310,12 +316,15 @@ export function useOverlayPosition(props: AriaPositionProps): PositionAria {
overlay.style.maxHeight = position.maxHeight != null ? position.maxHeight + 'px' : '';

// Restore scroll position relative to anchor element.
let activeElement = getActiveElement();
if (anchor && activeElement && scrollRef.current) {
let anchorRect = activeElement.getBoundingClientRect();
if (anchor && anchorElement && scrollRef.current) {
let anchorRect = anchorElement.getBoundingClientRect();
let scrollRect = scrollRef.current.getBoundingClientRect();
let newOffset = anchorRect[anchor.type] - scrollRect[anchor.type];
scrollRef.current.scrollTop += newOffset - anchor.offset;
} else if (scrollRef.current && savedScrollTop != null) {
// No focused element to anchor to (e.g. the user scrolled with the mouse), so restore
// the scroll position from before the max height was reset.
scrollRef.current.scrollTop = savedScrollTop;
}

// Trigger a set state for a second render anyway for arrow positioning
Expand Down Expand Up @@ -422,6 +431,30 @@ export function useOverlayPosition(props: AriaPositionProps): PositionAria {
};
}

/**
* Returns the element within the scroll container that currently has focus, either real DOM focus
* or virtual focus via aria-activedescendant (e.g. a ComboBox, where focus staus in the input).
*/

function getFocusedElementWithin(scrollNode: Element): Element | null {
let activeElement = getActiveElement();
if (!activeElement) {
return null;
}
if (isFocusWithin(scrollNode)) {
return activeElement;
}
let activeDescendantId = activeElement.getAttribute('aria-activedescendant');
if (activeDescendantId) {
let root = activeElement.getRootNode() as Document | ShadowRoot;
let activeDescendant = root.getElementById(activeDescendantId);
if (activeDescendant && nodeContains(scrollNode, activeDescendant)) {
return activeDescendant;
}
}
return null;
}

function useResize(onResize) {
useLayoutEffect(() => {
window.addEventListener('resize', onResize, false);
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -91,3 +91,59 @@ it.each(['fixed', 'absolute'] as const)(
}
}
);

it('preserves the scroll position of the scroll container when repositioning', async () => {
function Example() {
let targetRef = useRef<HTMLButtonElement>(null);
let overlayRef = useRef<HTMLDivElement>(null);
let scrollRef = useRef<HTMLDivElement>(null);
let {overlayProps} = useOverlayPosition({
targetRef,
overlayRef,
scrollRef,
placement: 'bottom left',
isOpen: true
});
return (
<>
<button ref={targetRef} style={{position: 'absolute', top: 200, left: 20, height: 30}}>
Trigger
</button>
{createPortal(
<div
ref={overlayRef}
{...overlayProps}
style={{...overlayProps.style, width: 200, display: 'flex'}}>
<div
ref={scrollRef}
data-testid="scroller"
style={{maxHeight: 'inherit', overflow: 'auto', flex: 1}}>
{Array.from({length: 100}, (_, i) => (
<div key={i} style={{height: 30}}>
Item {i + 1}
</div>
))}
</div>
</div>,
document.body
)}
</>
);
}

let result = await render(<Example />);
let scroller = document.querySelector('[data-testid="scroller"]') as HTMLElement;
await expect.poll(() => scroller.scrollHeight > scroller.clientHeight).toBe(true);

// Scroll to the bottom of the list.
scroller.scrollTop = scroller.scrollHeight;
let scrollTop = scroller.scrollTop;
expect(scrollTop).toBeGreaterThan(0);

// Trigger a reposition, as happens when the window is resized.
window.dispatchEvent(new Event('resize'));
await new Promise(resolve => requestAnimationFrame(resolve));

expect(scroller.scrollTop).toBe(scrollTop);
await result.unmount();
});